How to place values in a matrix with values from another matrix?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I have 2 tables A and B:
A B
2018 13 2018 0.2
2019 15 2019 0.3
2020 -76 2020 0.4
2021 -1 2020 0.6
2022 0 2020 0.1
2021 0.7
2021 0.1
I want to expand B by adding an additional column from A which is related to the first column of both tables: wherever the year (=column 1) is the same, the value from A(:,2) should be added in a 3rd column in B.
The new table B should thus look as follows:
A B
2018 13 2018 0.2 13
2019 15 2019 0.3 15
2020 -76 2020 0.4 -76
2021 -1 2020 0.6 -76
2022 0 2020 0.1 -76
2021 0.7 -1
2021 0.1 -1
Thank you in advance!
0 Kommentare
Antworten (2)
Arif Hoq
am 9 Mär. 2022
Bearbeitet: Arif Hoq
am 9 Mär. 2022
Year=[2018;2019;2020;2021;2022];
value1=[13;15;-76;-1;0];
table1=table2array(table(Year,value1))
Year2=[2018;2019;2020;2020;2020;2021;2021;];
value2=[0.2;0.3;0.4;0.6;0.1;0.7;0.1;];
table2=table2array(table(Year2,value2))
[idx out]=ismember(table2(:,1),table1(:,1));
newcol=table1(out,2);
newtable=table(Year2,value2,newcol)
0 Kommentare
Peter Perkins
am 9 Mär. 2022
This is a one-liner with join. You have time, so use a timetable:
>> year = datetime([2018;2019;2020;2021;2022],1,1); x = [13;15;-76;-1;0];
A = timetable(year,x)
A =
5×1 timetable
year x
___________ ___
01-Jan-2018 13
01-Jan-2019 15
01-Jan-2020 -76
01-Jan-2021 -1
01-Jan-2022 0
>> year = datetime([2018;2019;2020;2020;2020;2021;2021],1,1); y = [.2;.3;.4;.6;.1;.7;.1];
B = timetable(year,y)
B =
7×1 timetable
year y
___________ ___
01-Jan-2018 0.2
01-Jan-2019 0.3
01-Jan-2020 0.4
01-Jan-2020 0.6
01-Jan-2020 0.1
01-Jan-2021 0.7
01-Jan-2021 0.1
>> B = join(B,A,"Keys","year")
B =
7×2 timetable
year y x
___________ ___ ___
01-Jan-2018 0.2 13
01-Jan-2019 0.3 15
01-Jan-2020 0.4 -76
01-Jan-2020 0.6 -76
01-Jan-2020 0.1 -76
01-Jan-2021 0.7 -1
01-Jan-2021 0.1 -1
0 Kommentare
Siehe auch
Kategorien
Mehr zu Tables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!