MATLAB Answers

Can someone help with my syntax error

6 views (last 30 days)
I'm having trouble getting this to iterate through all rows of my matrix.
the goal is simply to be able to input a random matrix, and use 2 for loops to have the program locate and fprint the row and column index for all occurences of the integer. I can't use the find function, yes this is homework.
Brendan Clark
Brendan Clark on 4 Apr 2021
Thats good information to have, I appreciate the information and I'll make sure my future posts follow these guidelines.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 4 Apr 2021
We can't run or fix an image. But this will be useful to you instead of x and y
[rows, columns] = size(a)
for col = 1 : columns
for row = 1 : rows
if a(row, col) == 5
fprintf('a = %f at row=%d and column = %d.\n', a(row, col), row, col);
Or vectorized, using the find() function, which you're not allowed to use for this homework problem:
matchingMap = a == 5;
[matchingRows, matchingColumns] = find(matchingMap)

More Answers (3)

KSSV on 4 Apr 2021
If A is your array to count number of times a number n (say 5) appears, follow:
tol = 10^-5 ;
idx = abs(A-n)<=tol ;
  1 Comment
Brendan Clark
Brendan Clark on 4 Apr 2021
I don't think I phrased that well, the main goal is to use a set of for loops to find the row and column index for each occurence. The code I originally posted works for one row, but not multiple, I just need to get it to iterate through any avaialable rows.

Sign in to comment.

Walter Roberson
Walter Roberson on 4 Apr 2021
for b = 1 : numel(a)
Caution: length() is not the same as width() . If the array has more rows than columns, then the length() would be the number of rows, same as height()

Brendan Clark
Brendan Clark on 4 Apr 2021
I had attempted to use numel and still didn't get the correct outcome, this could have been due to another factor though.
I didn't realize that length was the same as height, thank you




Community Treasure Hunt

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

Start Hunting!

Translated by