How to fix the following: Index exceeds matrix dimensions issue?

% image 1:
image = fopen('image1.raw', 'r');
a1 = fread(image,'float32');
p1 = reshape(a1,100,100,100);
j = 0; X1 = 50; Y1 = 50; Z1 = 50;
for i = 1:1:49; j = j+1; mat = 0;
for k = 0:2:358;
x = i*cosd(k);
y = i*sind(k);
Xc = X1+(x/1);
Yc = Y1+(y/1);
XR1 = round(Xc);
YR1 = round(Yc);
mat = mat + p1(XR1,YR1,Z1);
energy = mat/180;
end
D(j,1) = i;
D(j,2) = (energy/(0.0005*0.0005*0.0005*1000));
end
% image 2
image = fopen('image2.raw', 'r');
a2 = fread(image,'float32');
p2 = reshape(a2,100,100,100);
j = 0; X2 = 50; Y2 = 50; Z2 = 50;
for i = 51:5:149; j = j+1;
for k = 0:2:358;
x = i*cosd(k);
y = i*sind(k);
Xc = X2+(x/1);
Yc = Y2+(y/1);
XR2 = round(Xc);
YR2 = round(Yc);
mat = p2(XR2,YR2,Z2); %---------------->>>>>> Index exceeds matrix dimension!!!
energy = mat/180;
end
D(j,1) = i;
D(j,2) = (energy/(0.0015*0.0015*0.0015*1000));
end

9 Comments

You forgot to attach the .raw images. Zip them up and attach them and maybe I'll check back later. Also, properly indent your code, which you can do in MATLAB by typing control-a control-i.
Thank you for an idea about indentation. Due to upload size limitation, I have made two .zip folders, please find two .raw images in it.
Your p2 size is 100*100*100 and you are trying to 101*50*50 element in the loop. So the error. You have to re-think about your loop indices. They should fall with in 100*100*100.
@ KSSV: I was unable to figure out how to solve this problem. Could you please point me how 100*100*100 becomes 101*50*50?
p2 becomes 100x100x100 in this line:
p2 = reshape(a2,100,100,100);
However, when you use mat = p2(XR2,YR2,Z2); there is a point in your for loop where XR2 = 101, YR2 = 50, and Z2 = 50. This is what KSSV was referring to. So you need to look at your definition of XR2 to make sure that it does not exceed 100, or to look at your reshape of p2 in order to make it 101x100x100.
@Bob: Could you please explain how XR2 and YR2 becomes 101 and 50?
It occurs on your first loop.
i = 51; k = 0; so x = 51*cosd(0) = 51 -> Xc = 50 + (51/1) = 101 -> XR2 = round(101) = 101.
y = 51*sind(0) = 0 -> Yc = 50 + (0/1) = 50 -> YR2 = round(50) = 50.
Could you please explain how XR2 and YR2 becomes 101 and 50?
If you can't figure it out yourself, then I recommend you use the debugger to step through your code one line at a time and see the actual values calculated.This is the most efficient way for you to understand why your program doesn't do what you expected it to do.
Thank you Bob and Guillaume for your help and advice.

Answers (0)

This question is closed.

Asked:

on 13 Nov 2018

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!