making a matrix from another one
조회 수: 1 (최근 30일)
이전 댓글 표시
i havematrix a=
1 2 3
4 5 6
7 8 9
i need to make a new matrix from a, i used the following code:
b=[];
for 1=1:3
for j=1:3
d=[a(i,j)]
b=[b;d];
end
end
but it gives me a 1x9 matrix,
i need b as a 3x3 matrix, with whole contents of a, i need to shape b like this: b=
1 2 3
4 5 6
7 8 9
where is my fault?
댓글 수: 0
답변 (2개)
Wayne King
2012년 9월 23일
편집: Wayne King
2012년 9월 23일
I'm not sure why you want to do this with a for loop since you are just creating a copy of the original matrix. You'd be much better off to do just:
b = a;
But if you must use a for loop:
b = zeros(3,3);
for ii =1:3
for jj =1:3
b(ii,jj)= a(ii,jj);
end
end
If you insist on doing it the way you did, then you have to do:
b = reshape(b,3,3)';
after you exit the loop:
b=[];
for ii =1:3
for jj =1:3
d=[a(ii,jj)];
b=[b;d];
end
end
b = reshape(b,3,3)';
nah
2012년 9월 23일
for i=1:3
for j=1:3
b(i,j) = a(i,j);
end
end
The fault is that you haven't defined the end the a row anywhere.
d=[a(i,j)]
b=[b;d];
d becomes a(i,j) and the element goes into b, which becomes a vector of 9 elements;
what is preventing you from simply doing ,
b = a; ?
or b(i,j) = a(i,j) ?
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!