Printing Results out of a for Loop
Show older comments
I have Written a Small Function that Returns the Absolute Difference Between the Max and Min Elements of Each Row in a Matrix and Assigns the Results to the output "rows_diff" as Row Vector and Also Gets the Diff. Between the Max and Min of Whole Matrix in "tot_diff"
All what I want to Know is How to Print Out the Results of the for Loop Returning them in "rows_diff" as row vector not just the Last Result as the Case with this Version of the Function:-
function [rows_diff, tot_diff] = minimax(M)
a = size(M,1);
for i = 1:a
rows_diff = abs(max(M(i,:)) - min(M(i,:)));
end
tot_diff = max(M(:)) - min(M(:));
2 Comments
Note that avoiding the loop gives simpler, more efficient code:
>> M = magic(5) % fake data.
M =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> minimax(M) % function with loop (following Ruger28's bugfix).
ans =
23 18 18 18 23
>> max(M,[],2) - min(M,[],2) % no loop required, more efficient.
ans =
23
18
18
18
23
Ammar Taha
on 27 Jun 2019
Accepted Answer
More Answers (2)
Alex Mcaulley
on 27 Jun 2019
You can also implement the function in a simpler and efficient way:
function [rows_diff, tot_diff] = minimax(M)
rows_diff = arrayfun(@(i) abs(max(M(i,:)) - min(M(i,:))),1:size(M,1))';
tot_diff = max(M(:)) - min(M(:));
end
3 Comments
Stephen23
on 27 Jun 2019
"You can also implement the function in a simpler and efficient way:"
arrayfun is unlikely to be an efficient approach (1e5 iterations, 12x12 matrix):
Elapsed time is 8.715833 seconds. % Ruger28's bugfix (no preallocation).
Elapsed time is 6.902387 seconds. % Ruger28's bugfix (preallcoated).
Elapsed time is 21.641814 seconds. % your ARRAYFUN solution.
Elapsed time is 0.597622 seconds. % my solution without a loop.
Ammar Taha
on 27 Jun 2019
Ammar Taha
on 27 Jun 2019
Ammar Taha
on 27 Jun 2019
0 votes
1 Comment
Ruger28
on 27 Jun 2019
no problem, glad to be of some help.
Categories
Find more on Loops and Conditional Statements 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!