Matrix dimensions must agree

When I run this code:
[m,n,p]=size(func_data);
mir_data=zeros(m,n,length(mir_time));
pl_data=zeros(m,n,length(pl_time));
for i=1:length(mir_time)
mir_data(:,:,i)=func_data(:,:,mir_time(i,1));
end
for i=1:length(pl_time)
pl_data(:,:,i)=func_data(:,:,pl_time(i,1));
end
mask=zeros(90,180);
for i=1:120
img_pl=pl_data(:,:,i);
img_pl=img_pl-min(img_pl(:));
imax=max(img_pl(:));
img_pl=floor(64*img_pl/(imax+1));
img_mir=mir_data(:,:,i);
img_mir=img_mir-min(img_mir(:));
imax=max(img_mir(:));
img_mir=floor(64*img_mir/(imax+1));
img_diff=img_mir-img_pl;
mask=mask+img_diff;
end
I get the error:
Matrix dimensions must agree.
Error in Untitled (line 35)
mask=mask+img_diff;
I do not understand why I am getting this error here. According to the Workspace both mask and img_diff are 90 x 108 so I do not see where the problem is. I am trying to get the difference of each corresponding pixel for all the 90 X 108 2D arrays in "mir_data" and "pl_data" and saving the accumulated sum in "mask". Is there a way I can do this without triggering this error?

1 个评论

what is size of func_data? To test/run the code we need to know this.

请先登录,再进行评论。

回答(2 个)

An img_diff of 90 x 108 would be incompatible with a mask of 90 x 180.
Here is some sample data that is certain to not lead to a problem:
S = randi(1000,1,1);
T = 120 + randi([0, 1000]);
U = 120 + randi([0, 1000]);
func_data = rand(90, 180, S); %rows and columns must be exactly these
mir_time = randi(S,T,1); %anything past 120 will be ignored for the mask
pl_time = randi(S,U,1); %anything past 120 will be ignored for the mask

2 个评论

Thank you for the quick response. I am trying to add up the differences each corresponding point of mir_data and pl_data then accumulate them in the mask array? Is there a way to do this which will not lead to the error?
Your code does something without error provided that func_data is 90 x 180 x something. Your earlier description suggests that func_data might be 90 x 108 x something -- notice 108 compared to 180.

请先登录,再进行评论。

Guillaume
Guillaume 2017-5-12
编辑:Guillaume 2017-5-12
"Is there a way to do this which will not lead to the error?"
There's a very simple way: Never ever hardcode the size of the matrix in your code. You know that mask must be the same size as img_diff which is the same size as img_pl and img_mir which in turn are the same size as pl_data(:, :, 1). So, create mask that size and you'll be sure that your code works whatever the size of your input:
mask = zeros(size(pl_data(:, :, 1)));
%or
%mask = zeros(m, n)
%since that's how you created pl_data

类别

在 帮助中心 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by