How to compare two arrays and add elements to the first one

조회 수: 4 (최근 30일)
Patrick Benz
Patrick Benz 2021년 2월 12일
댓글: Patrick Benz 2021년 2월 12일
I've got two arrays of different dimensions. The first is a 41x4 and the other one a 400000x4.
I would like to find those rows where the element in the first column in the same in both arrays and either add the entries from the last three columns to the first array or, if it is easier, write the whole row of the second array into a new array and proceed.
Is there an easier way to do this without two loops? Because I don't like to run through 400k elements 40 times.
As en example:
Array 1: 990 0 0 0
991 0 0 0
Array 2: 991 5 7 3
What I want:
990 0 0 0
991 5 7 3

채택된 답변

dpb
dpb 2021년 2월 12일
You were on the right track...
[LIA,LOCB]=ismember(A1(:,1),A2(:,1)); % find locations in respective arrays first column
A1(LIA,:)=A2(LOCB(LIA),:); % replace the matched rows in A1 with A2

추가 답변 (1개)

Patrick Benz
Patrick Benz 2021년 2월 12일
There are probably more elegant ways, I got what I wanted by using following code:
[LIA,LOCB]=ismember(elNum,node_Num)
Auswertung=zeros(length(LOCB),4)
for i=1:length(LOCB)
index=LOCB(i,1)
Auswertung(i,1)=node_Num(index,1);
Auswertung(i,2)=node_Num(index,2);
Auswertung(i,3)=node_Num(index,3);
Auswertung(i,4)=node_Num(index,4);
end

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by