Effacer les filtres
Effacer les filtres

Insert data into the right index

1 vue (au cours des 30 derniers jours)
Jeon
Jeon le 11 Avr 2013
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
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.

Connectez-vous pour commenter.

Réponses (2)

Yao Li
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
Yao Li
Yao Li le 11 Avr 2013
try the function find, but I think you still need one for loop
Jan
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".

Connectez-vous pour commenter.


Andrei Bobrov
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,:);

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by