making a matrix from another one

2 ビュー (過去 30 日間)
babak
babak 2012 年 9 月 23 日
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?

回答 (2 件)

Wayne King
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)';
  1 件のコメント
babak
babak 2012 年 9 月 23 日
編集済み: babak 2012 年 9 月 23 日
actually its a simplified example. my exact work is :
>> enz=[];
>> enz=zeros(8,3);
>> for ii=1:14
for jj=1:3
match=ismember(file1,rxn)
if match(ii)==1
enz(ii,jj)=rxn(ii,jj)
end
end
end
i corrected my code according to your advise, but it doesont work, rxn is 14x3, and file1 is 8x1 . i found the contents of the file1 in rxn and now i'm going to copy the whole contents of related rows(the rows that contains the same contents) in rxn to a new matrix, which should creat a 8x3 matrix, but i cant shape this matrix

サインインしてコメントする。


nah
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) ?

カテゴリ

Help Center および File ExchangeData Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by