Insert data into the right index

2 次查看(过去 30 天)
Jeon
Jeon 2013-4-11
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 个评论
Jan
Jan 2013-4-11
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.

请先登录,再进行评论。

回答(2 个)

Yao Li
Yao Li 2013-4-11
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 个评论
Yao Li
Yao Li 2013-4-11
try the function find, but I think you still need one for loop
Jan
Jan 2013-4-11
编辑:Jan 2013-4-11
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
Andrei Bobrov 2013-4-11
编辑:Andrei Bobrov 2013-4-11
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,:);

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by