making a matrix from another one

2 vues (au cours des 30 derniers jours)
babak
babak le 23 Sep 2012
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?

Réponses (2)

Wayne King
Wayne King le 23 Sep 2012
Modifié(e) : Wayne King le 23 Sep 2012
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 commentaire
babak
babak le 23 Sep 2012
Modifié(e) : babak le 23 Sep 2012
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

Connectez-vous pour commenter.


nah
nah le 23 Sep 2012
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) ?

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by