Clear Filters
Clear Filters

What is the meaning of an error "Matrix dimension must agree?"

1 view (last 30 days)
Why i got that error when i tried to load an image? Can someone explain me about that error & how can i solve the error?

Accepted Answer

Walter Roberson
Walter Roberson on 6 Oct 2016
Suppose you had something like:
A = zeros(64, 80, 5);
B = randi([0 255], 60, 72);
and you tried to do
A(:,:,2) = B;
Although in this case B would fit entirely inside A(:,:,2), B is not the same size as A(:,:,2) so MATLAB complains the the dimensions (size) of the area being stored into is not the same as the dimensions (size) of what is being stored.
In a case like the above, you could use
A(1:size(B,1), 1:size(B,2), 2) = B;
Sometimes people try to do something like
for K = 1 : 10
filename = sprintf('Image%d.jpg', K);
images(:,:,:,K) = imread(filename);
end
This works fine when all of the images stored in the files are exactly the same size, but it fails if the images are not exactly the same size. For example the first 8 in a row might be all the same 1024 x 768 x 3 (the x 3 is for RGB), but the 9th one might be stored as 1024 x 767 x 3 for some reason, and cannot be simply stored covering all of the 9th slice. You need an arrangement like
for K = 1 : 10
filename = sprintf('Image%d.jpg', K);
this_image = imread(filename);
images(1:size(this_image,1), 1:size(this_image,2), 1:size(this_image,3)) = this_image;
end
or alternately something like
for K = 1 : 10
filename = sprintf('Image%d.jpg', K);
images(:,:,:,K) = imresize(imread(filename), [1024 768]); %force them all to be the same size
end
One of the more common ways that images can end up different sizes is if people write them out in a loop from a capture of some graphics, something like
for K = 1 : 10
plot(t, sin(K * 2 * Pi * t));
title( sprintf('frequency %d', K) );
filename = sprintf('Image%d.jpg', K);
saveas(gca, filename);
end
And then they read the files back in, expecting them to be all the same size. Unfortunately, if you are not careful, then the size of the image saved through the various graphics capture mechanisms can vary from plot to plot. For example when K reached 10, the number of characters in the title() would change and that could result in the image being slightly wider. And that might not show up until you tried to read all of the images into one array (such as to create a movie.)
  1 Comment
Alvindra Pratama
Alvindra Pratama on 1 Nov 2016
Thank you for answered my question sir, I am sorry because i can answer now because I forgot my account password

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!