Duplicate a matrix using nested for loops

In Matlab I have been trying to duplicate matrix A [2,4,1;6,7,2;3,5,9] to matrix B using nested for loops. I know the general format uses an algorithm within the loop ie.
m=3
n=3
b=zeros(m,n)
for i=1:m
for j=1:n
B(m,n)= *algorithm here*
end
end
I can not find an algorithm that would work for this matrix and I believe that it was designed this way on purpose. I have tried pulling numbers out of matrix A using
A=[2,4,1;6,7,2;3,5,9]
for c=A(1,:)
for d=A(2,:)
for e=A(3,:)
end
end
end
B=[c;d;e]
but this just assigns the values for the last column of A to a 1x3 matrix B (B=[1;2;9]
I have also tried scouring the www for help with how to duplicated a matrix that is not algorithmic using nested for loops to no avail.
Any help or guidance would be much appreciated.

댓글 수: 1

Stephen23
Stephen23 2018년 2월 20일
???
Why not just avoid the pointless loops and use B=A ?

댓글을 달려면 로그인하십시오.

 채택된 답변

Roger Stafford
Roger Stafford 2018년 2월 20일

0 개 추천

What's wrong with
B = A; % ?
However, if you absolutely must do it with nested for-loops then do:
[m,n] = size(A);
B = zeros(m,n);
for i1 = 1:m
for i2 = 1:n
B(i1,i2) = A(i1,i2);
end
end
_

댓글 수: 3

Tyler M
Tyler M 2018년 2월 20일
I agree that B=A is a much simpler solution but the point was to learn additional functions in Matlab. I don't know why my boneheaded self didn't think to use B=A as the expression in the for loops but that would be way too easy right? Thanks a lot for the help Mr. Stafford.
Roger Stafford
Roger Stafford 2018년 2월 20일
편집: Roger Stafford 2018년 2월 20일
You wouldn't want to use just B=A inside those for-loops. That would be extremely wasteful of computing time. B=A by itself does the job without for-loops. Using for-loops with B(i1,i2) = A(i1,i2); is bad enough.
Tyler M
Tyler M 2018년 2월 20일
I see your points. I will definitely keep these in mind while writing code in the future!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Parallel Computing Toolbox에 대해 자세히 알아보기

제품

질문:

2018년 2월 20일

댓글:

2018년 2월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by