How do I get the for loop to run correctly?
Show older comments
A = [1, 2, 3;4,5,6];
result = zeros(size(A));
for k = [1:2]
result = strcat(num2str(A(k,1)),num2str(A(k,2)),num2str(A(k,3)));
k = k+1;
end
The aim of the above code is to combine three single digits to one 3-digit number. The result I expect is [123;456] but instead I am getting only [456]. Also when i check the value of k after running it, it says k =2. Please what is wrong with my code?
Accepted Answer
More Answers (1)
Walter Roberson
on 2 Mar 2017
result = strcat(num2str(A(k,1)),num2str(A(k,2)),num2str(A(k,3)));
is writing over all of the variable result in the loop. You want to instead write to one row of it, result(k,:) = ...
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!