Insert data into the right index
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have two matrices:
A = [1 3 5 7 9;
NaN NaN NaN NaN NaN];
B = [1 5 9;
x y z];
The first row of each matrices is a some sort of 'index'
I'd like to move (or copy) [x y z] into the second row of matrices A with the same indices:
A = [1 3 5 7 9;
x NaN y NaN z];
I'm happy if your solution / answer works well for larger matrices
1 commentaire
Jan
le 11 Avr 2013
What is the contents of B? You cannot mix doubles like 1 with characters like 'y' in an array, but you'd need a cell for this.
Réponses (2)
Yao Li
le 11 Avr 2013
clear;
clc;
x=10;
y=20;
z=30;
A = [1 3 5 7 9;
NaN NaN NaN NaN NaN];
B = [1 5 9;
x y z];
for i=1:length(A(1,:))
for j=1:length(B(1,:))
if A(1,i)==B(1,j)
A(2,i)=B(2,j);
else
end
end
end
A
3 commentaires
Jan
le 11 Avr 2013
Modifié(e) : Jan
le 11 Avr 2013
Neither clear nor clc are useful here.
At least one loop can be removed easily:
for iB = 1:length(B(1,:))
A(2, A(1, :) == B(1, iB)) = B(2, iB);
end
Does this work, when an element of B is not found? If not, use:
for iB = 1:length(B(1,:))
match = A(1, :) == B(1, iB);
if any(match)
A(2, match) = B(2, iB);
end
end
It is recommended to avoid "i" and "j" as variables, because they represent the sqrt(-1) also. In addition confusing "i" and "j" inside a loop is a famous programming error, which can be avoided by the more meaningful names "iA" and "iB".
Andrei Bobrov
le 11 Avr 2013
Modifié(e) : Andrei Bobrov
le 11 Avr 2013
for cell array
A = {1 3 5 7 9;
NaN NaN NaN NaN NaN};
B = {1 5 9;
'x' 'y' 'z'};
A(2,ismember([A{1,:}],[B{1,:}])) = B(2,:);
or
for double array
A = [1 3 5 7 9;
NaN NaN NaN NaN NaN];
B = [1 5 9;
100 500 900];
A(2,ismember(A(1,:),B(1,:))) = B(2,:);
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!