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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by