fprintf with two variables goes completely through the first variable instead of alternating
3 views (last 30 days)
Show older comments
Here's my code, it's supposed to print the row and column location of the values of matrix x greater than 10.
x=[1 10 42 6
5 8 78 23
56 45 9 13
23 22 8 9];
[xgt10row,xgt10col]=find(x>10)
disp('element location of values of x greater than 10')
fprintf('row %d col %d \n',xgt10row,xgt10col)
it outputs
element location of values of x greater than 10
row 3 col 4
row 3 col 4
row 1 col 2
row 2 col 3
row 1 col 1
row 2 col 2
row 3 col 3
row 4 col 4
which is basically going through the entirety of xgt10row before moving on to xgt10col.
I thought it would pick the first element of xgt10row, then the first element of xgt10col, etc.
My solution was to instead do
fprintf('row %d col %d \n',[xgt10row';xgt10col'])
which outputs
element location of values of x greater than 10
row 3 col 1
row 4 col 1
row 3 col 2
row 4 col 2
row 1 col 3
row 2 col 3
row 2 col 4
row 3 col 4
which is correct.
Is there a reason it has to be this way and is there a neater way to do it?
1 Comment
Stephen23
on 13 Apr 2023
Edited: Stephen23
on 13 Apr 2023
"Is there a reason it has to be this way..."
The FPRINTF documentation states that it "applies the formatSpec to all elements of arrays A1,...An in column order" (bold added). In other words, it processes the array content in the order that they are stored in memory. When it runs out of elements of the 1st input array then it moves on to the 2nd input array, and so on.
"...and is there a neater way to do it?"
Transpose once rather than twice:
x = [1,10,42,6;5,8,78,23;56,45,9,13;23,22,8,9];
[xgt10row,xgt10col] = find(x>10);
fprintf('row %d col %d \n',[xgt10row,xgt10col].')
Accepted Answer
VBBV
on 13 Apr 2023
x=[1 10 42 6
5 8 78 23
56 45 9 13
23 22 8 9]
[xgt10row,xgt10col]=find(x>10)
disp('element location of values of x greater than 10')
for k = 1:length(xgt10col)
fprintf('row %d col %d \n',xgt10row(k), xgt10col(k))
end
2 Comments
VBBV
on 13 Apr 2023
x=[1 10 42 6
5 8 78 23
56 45 9 13
23 22 8 9];
[xgt10row,xgt10col]=find(x>10);
disp('element location of values of x greater than 10')
%without using for loop
fprintf('row %d col %d \n',[xgt10row.'; xgt10col.'])
More Answers (0)
See Also
Categories
Find more on Multidimensional Arrays 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!