Horizontal concatenation of sub-matrix into a bigger matrix based on value of first column

4 visualizaciones (últimos 30 días)
Hi I have three dissimilar size array which I am retrieving through a loop, in which the first column contains year and the second column contains value in the next column. I want to concatenate all three sub-matrices based on the year value on the first column. For example, the three matrix A, B and C are as below. The desired output matrix is D.
A = [1950 0.463
1951 0.417
1952 0.468
1953 0.599
1954 0.582
1955 0.518
1956 0.400
1957 0.569
1958 0.498
1959 0.588]
B = [1955 0.567
1956 0.494
1957 0.636
1958 0.534
1959 0.674]
C = [1949 0.6848
1950 0.6408
1951 0.5976
1952 0.6163
1953 0.7335
1954 0.7058
1955 0.6593
1956 0.5601
1957 0.6901
1958 0.6056
1959 0.7390
]
The desired matrix is D:
D = [1949 Nan 0.6848 Nan
1950 0.463 0.6408 Nan
1951 0.417 0.5976 Nan
1952 0.468 0.6163 Nan
1953 0.599 0.7335 Nan
1954 0.582 0.7058 Nan
1955 0.518 0.6593 0.567
1956 0.4 0.5601 0.494
1957 0.569 0.6901 0.636
1958 0.498 0.6056 0.534
1959 0.588 0.739 0.674
]
How can I concatenate them based on the year value on the first column? Any help would be appreciable. Thanks

Respuesta aceptada

Stephen23
Stephen23 el 16 de Oct. de 2018
Editada: Stephen23 el 16 de Oct. de 2018
Using unique and accumarray:
>> A(:,3) = 1; % select output column.
>> B(:,3) = 3; % select output column.
>> C(:,3) = 2; % select output column.
>> M = [A;B;C];
>> [U,~,X] = unique(M(:,1));
>> D = accumarray([X,M(:,3)],M(:,2),[],[],NaN)
D =
NaN 0.68480 NaN
0.46300 0.64080 NaN
0.41700 0.59760 NaN
0.46800 0.61630 NaN
0.59900 0.73350 NaN
0.58200 0.70580 NaN
0.51800 0.65930 0.56700
0.40000 0.56010 0.49400
0.56900 0.69010 0.63600
0.49800 0.60560 0.53400
0.58800 0.73900 0.67400
>> D = [U,D]
D =
1949 NaN 0.68480 NaN
1950 0.46300 0.64080 NaN
1951 0.41700 0.59760 NaN
1952 0.46800 0.61630 NaN
1953 0.59900 0.73350 NaN
1954 0.58200 0.70580 NaN
1955 0.51800 0.65930 0.56700
1956 0.40000 0.56010 0.49400
1957 0.56900 0.69010 0.63600
1958 0.49800 0.60560 0.53400
1959 0.58800 0.73900 0.67400

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by