MATLAB Answers

error: Index exceeds the number of array elements (1).

8 views (last 30 days)
Sudha R Jogin
Sudha R Jogin on 26 Jul 2021
Commented: Sudha R Jogin on 26 Jul 2021
close all;
workspace;
vid= VideoReader('sony.mp4');
F= vid.NumFrames;
sum=0;
for i=1:F
video = read (vid,i);
[rows , columns ]= size (video(i));
noisyvideo(i)= imnoise(video(i),"gaussian",0,0.02);
squareErrorFrame(i) = (double(noisyvideo(i))-double(video(i))).^2;
MSE = sum(sum (squareErrorFrame(i)))/(rows*columns);
sum= sum + MSE;
end
display(sum);
Index exceeds the number of array elements (1).
Error in forloopTrail (line 11)
MSE = sum(sum (squareErrorFrame(i)))/(rows*columns);

Answers (1)

Jan
Jan on 26 Jul 2021
Edited: Jan on 26 Jul 2021
Do not use the name "sum" for a variable. Avterwards the function with the same name is shadowed:
clear sum
sum(1:10) % working
sum = 0
sum(1:10) % failing
So simply rename your variable "sum":
sumMSE = 0;
...
sumMSE = sumMSE + MSE;
If your code is a script, "sum" has been shadowed in the base workspace. Then clean it up by:
clear sum
A general hint: Use functions instead of scripts, such that shadowed functions do not have unexpected effects in other scripts, where they are extremly confusing. Shadowing important built-in function is a frequent problem, so avoid this as good as possible.
Are you sure, that this is wanted:
[rows , columns] = size(video(i));
% ^^^ ?!
With
noisyvideo(i) = imnoise(video(i),"gaussian",0,0.02);
the array noisyvideo is growing in each iteration. The editor should show you a hint. This is extremly expensive. Example:
x = [];
for k = 1:1e6
x(k) = k;
end
Although the resulting vector needs 8MB only (8 bytes per double), Matlab has to create a new vector in each iteration and copies the elements of the former ones. So in totel Matlab allocates sum(1:1e6)*8 bytes and copys almost the same amoubnt of memory: More than 4 Terabyte!
Solution: Either preallocate:
x = zeros(1, 1e6); % Pre-allocate
for k = 1:1e6
x(k) = k;
end
Or if you do not need all x, do not store them:
for k = 1:1e6
x = k;
... something can be done with x here
end
In your case I guess using noisyvideo without (i) is sufficient.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!