Insert data into the right index

1 visualización (últimos 30 días)
Jeon
Jeon el 11 de Abr. de 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 comentario
Jan
Jan el 11 de Abr. de 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.

Iniciar sesión para comentar.

Respuestas (2)

Yao Li
Yao Li el 11 de Abr. de 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 comentarios
Yao Li
Yao Li el 11 de Abr. de 2013
try the function find, but I think you still need one for loop
Jan
Jan el 11 de Abr. de 2013
Editada: Jan el 11 de Abr. de 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".

Iniciar sesión para comentar.


Andrei Bobrov
Andrei Bobrov el 11 de Abr. de 2013
Editada: Andrei Bobrov el 11 de Abr. de 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,:);

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by