I am having trouble calling the following code:
% Load image and convert image to array
img = imread(imgPath);
% Get the size of the image
imageSize = size(img);
It crashes at the second line, with the error:
Array indices must be positive integers or logical values.
imageSize = size(img);
I've tried checking the path is correct, it is.
I've tried isempty() on img, it's not
I've tried resaving the image to the project folder, it looks fine.
I've tried checking the format it's in, it's uint8
I've tried disp(img) and it says:
(:,:,1) =
Columns 1 through 23
208 209 210 212 213 214 214 214 213 213 213 214 214 214 215 215 217 217 217 217 217 217 217
... for many more lines
Please can someone tell me what I'm doing wrong

 Accepted Answer

Voss
Voss on 13 May 2024
Edited: Voss on 13 May 2024

1 vote

You have a variable called "size".

If this is a script, do

clear size

and then run the script again.

If this is a function, rename your size variable to another name that's not a function's name.

4 Comments

You're correct thank you so much, did not stand a chance of figuring that out from the error message alone
Voss
Voss on 13 May 2024
Edited: Voss on 13 May 2024
You're welcome!
Well, if you run into this same situation in the future, you'll know what to do now!
By way of further explanation: The error message mentions "indices", indicating that MATLAB is attempting to do an indexing operation on that line, which is obviously not what you intended. From that (and from the experience of having run into this situation a few times before), you can conclude that MATLAB thinks "size" is a variable and "img" is some indices, in which case "size(img)" means to get the elements of the size variable at the indices given by img, as opposed to meaning run the size function with img as the input, which has the same syntax. This page lists function precedence order, and you can see there that variables are first, so if you have a variable with the same name as a function, MATLAB's going to use the variable. (And I guess there are some zero elements in img, which is the reason for the actual error; you might also have run into the "index exceeds array bounds" error in this situation.)
Thank you for the explanation - though as a matlab newbie most of that still goes over my head even when you explain it to me! Like what you've said makes sense but I couldn't apply it on my own.
I'm used to the compiler telling me what's wrong, like when I defined the variable 'size' it might have shown me a warning saying that it overlaps a function name from my project.
Anyway thanks again!
Voss
Voss on 13 May 2024
You're welcome!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 13 May 2024

Commented:

on 13 May 2024

Community Treasure Hunt

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

Start Hunting!