Add cell value from a matrix row based on corresponding index to another matrix row

1 view (last 30 days)
I have two arrays A and B.
Column 1 of array A contain the index number of the samples; other columns of matrix A contain other attributes of each sample, (in array B, the first two cell along each row contain an attribute and the index number of a sample)
Columns 2, 4 and 6 of array B contain the index number of samples contained in matrix A.
I am trying to insert corresponding sample attribute in column 4 of array A (based on coresponding index number in array A and B) into new 3rd, 6th and 9th column of matrix B; to have matrix C as shown below:
A = [1,3.43,2.34,5.43,3.22;
2,8.32,6.34,7.34,2.34;
3,3.67,8.34,8.23,1.34;
4,2.67;6.89,4.99,8.65;
5,1.33,5.42,2.53,6.13]
B = [ 0.12,2,0.15,1,0.65,3;
0.33,5,0.62,4,0.55,1;
0.91,1,0.77,2,0.66,5]
C = [ 0.12,2,7.34,0.15,1,5.43,0.65,3,1.34;
0.33,5,2.53,0.62,4,4.99,0.55,1,5.43;
0.91,1,5.43,0.77,2,7.34,0.66,5,2.53]
I have tried the following code but got an error:
For i= 1:3
f=ismember(A(:,1(i)), B(:,2), 'rows');
k=find(f);
f=A(f,4);
C= [C,f(i)]
end

Accepted Answer

Guillaume
Guillaume on 21 Mar 2019
If you want to keep using numeric matrices:
[~, whereinA] = ismember(B(:, [2 4 6]), A(:, 1))
C = reshape([reshape(B.', 2, []); A(whereinA, 4).'], 9, []).'
However, you may want to switch to tables since all your columns seem to represent different things:
A = [1,3.43,2.34,5.43,3.22;
2,8.32,6.34,7.34,2.34;
3,3.67,8.34,8.23,1.34;
4,2.67,6.89,4.99,8.65;
5,1.33,5.42,2.53,6.13];
B = [ 0.12,2,0.15,1,0.65,3;
0.33,5,0.62,4,0.55,1;
0.91,1,0.77,2,0.66,5];
tA = array2table(A, 'VariableNames', {'Sample', 'SomeProp', 'OtherProp', 'Prop3', 'LastProp'})
tB = array2table(B, 'VariableNames', {'StartValue', 'StartSample', 'MidValue', 'MidSample', 'EndValue', 'EndSample'})
tC = tB;
for samp = 1:3
tC = join(tC, tA, 'LeftKeys', tB.Properties.VariableNames{samp*2}, 'RightKeys', 'Sample', 'RightVariables', 'Prop3');
end
tc.Properties.VariableNames(end-2:end) = {'StartProp3', 'MidProp3', 'EndProp3'};
it may be longer, but make it clearer what is happening and you end up with output that is more readable.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!