making a matrix from another one
2 ビュー (過去 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!