Filter löschen
Filter löschen

Insert data into the right index

2 Ansichten (letzte 30 Tage)
Jeon
Jeon am 11 Apr. 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 Kommentar
Jan
Jan am 11 Apr. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

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

Melden Sie sich an, um zu kommentieren.


Andrei Bobrov
Andrei Bobrov am 11 Apr. 2013
Bearbeitet: Andrei Bobrov am 11 Apr. 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,:);

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by