invalid index in find function
2 views (last 30 days)
Show older comments
Timothy Dunning
on 23 Feb 2023
Edited: Walter Roberson
on 25 Feb 2023
Wrote this function to detect a line on a .png file of a graph, read the coordinates and use them to recalculate the graph data:
function TC = fileReadTest()
%set data at graph limits
Tfmax = 2000;
tmax = 2000;
[pixels]=imread("temp597.jpg"); % read rgb values for each pixel on graph
imshow(pixels)
[x_axes,y_axes]=ginput(2);% select axes limits (y limit then x limit)
data(2,x_axes(2)-x_axes(1)) = zeros; %define the length of the data list
for column=x_axes(1):x_axes(2) %loop for each column inside the graph
%find the first red(ish) pixel in the column
[row, col]=find(pixels(:,column,1)>200 && pixels(:,column,2)<50,1,'first');
if (col == column) %append data list if red pixel is found in the column
data(:,col) = [row;col]-[x_axes(1);y_axes(2)];
end
end
% convert data coordinate to usable value
Tf=[Tfmax/(y_axes(1)-y_axes(2))*data(1,:);tmax/(x_axes(2)-x_axes(1))*data(2,:)];
TC=(Tf(1,:)-32)*5/9;
got the following error:
Index in position 2 is invalid. Array indices must be positive
integers or logical values.
Error in fileReadTest (line 14)
[row, col]=find(pixels(:,column,1)>200 && pixels(:,column,2)<50,1,'first');
0 Comments
Accepted Answer
Steven Lord
on 23 Feb 2023
There's no guarantee that the elements of x_axes (the points that you selected using ginput) are integer values. Therefore there's no guarantee that the values assigned to your loop variable column are integer values. MATLAB can't index into the 125.3827th column (as an example) of your pixels array.
Perhaps it would be sufficient if you were to round those coordinates before using them in your loop.
3 Comments
Steven Lord
on 25 Feb 2023
You can't use the short-circuiting && or || operators when either of the inputs you're operating on are non-scalars. [If you could, and the first input contained a mix of true and false values, should the second input only be evalated for those elements where their values could change what the logical operators return? That could get very messy very quickly.]
Use the non-short circuiting & or | operators instead.
x = 1:10;
y = 10:-1:1;
z = (x > 3) & (y > 4)
[x; y; z]
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!