How do I get the for loop to run correctly?

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

out = A*10.^(size(A,2)-1:-1:0)'; % in your case
other [EDIT]
n = floor(log10(A(:,2:end)))+1;
n = [n, zeros(size(A,1),1)];
out = sum(A.*10.^cumsum(n,2,'r'),2);
% using
>> A =[ 60 110 49
17 9 91];
>> n = floor(log10(A(:,2:end)))+1;
n = [n, zeros(size(A,1),1)];
out = sum(A.*10.^cumsum(n,2,'r'),2)
out =
6011049
17991
>>
or
out = mat2cell(sprintf('%d',A'),1,sum(floor(log10(A))+1,2)')';

More Answers (1)

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

Asked:

N/A
on 2 Mar 2017

Commented:

N/A
on 2 Mar 2017

Community Treasure Hunt

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

Start Hunting!