user1487735
user1487735

Reputation: 81

Create a matrix using elements of other matrices in MATLAB

I have two matrices a and b (with equal number of columns). I want to create a third matrix c using a condition:

For example, I have:

a = [1  2  3  4  1  2  3  4  1  2  3  4; 
     1  1  1  1  2  2  2  2  3  3  3  3]

b = [5  6  7  8  9  10 11 12 13 14 15 16;    
     17 18 19 20 21 22 23 24 25 26 27 28;    
     29 30 31 32 33 34 35 36 37 38 39 40]

The condition is: a(2, :) == 2, so the resulting matrix should be:

c = [1 2 3 4;
     2 2 2 2;
     9 10 11 12;
     21 22 23 24;
     33 34 35 36]

Upvotes: 1

Views: 1650

Answers (2)

Ben A.
Ben A.

Reputation: 1039

Here's something that should work. By all means probably not the best and most efficient way to do it.

a=[1 2 3 4 1 2 3 4 1 2 3 4;  
   1 1 1 1 2 2 2 2 3 3 3 3];

b=[5 6 7 8 9 10 11 12 13 14 15 16;     
  17 18 19 20 21 22 23 24 25 26 27 28;     
  29 30 31 32 33 34 35 36 37 38 39 40];

truthtable = a(2,:)==2;
c = []
for idx = 1:length(truthtable)
    if truthtable(idx) == 1
       c(:,end+1) = [a(:,idx);b(:,idx)];
    end
end

Upvotes: 0

Not Bo Styf
Not Bo Styf

Reputation: 411

Try this

%With your a and b

cols = a(2,:) == 2;
c = [a(:,cols) ; b(:,cols)];

c =

 1     2     3     4
 2     2     2     2
 9    10    11    12
21    22    23    24
33    34    35    36

Upvotes: 5

Related Questions