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

3 Ansichten (letzte 30 Tage)
Patrick Benz
Patrick Benz am 12 Feb. 2021
Kommentiert: Patrick Benz am 12 Feb. 2021
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

Akzeptierte Antwort

dpb
dpb am 12 Feb. 2021
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

Weitere Antworten (1)

Patrick Benz
Patrick Benz am 12 Feb. 2021
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

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by