0
votes

Im using matlab and I have a matrix

1  1
2  1
3  1
4  2
5  2
6  2
7  1
8  1
9  2
10  2
11  2

How can i copy matrix from second column but only certain number? the other number will be random either 1 or 2. Example

1  1  1   |     | 1  1  1
2  1  1   |     | 2  1  1
3  1  1   |     | 3  1  1
4  2  2   |     | 4  2  2
5  2  1   |  OR | 5  2  2
6  2  1   |     | 6  2  1 
7  1  1   |     | 7  1  1 
8  1  1   |     | 8  1  1
9  2  2   |     | 9  2  2
10 2  2   |     |10  2  1
11 2  1   |     |11  2  1  

If the third row of 2 become 1, the rest of the column will become 1. process repeat until it reach another set of 2

2

2 Answers

0
votes

You can use the logical indexing and the function randi:

   a = [1  1;
    2  1;
    3  1;
    4  2;
    5  2;
    6  2;
    7  1;
    8  1;
    9  2;
    10  2;
    11  2];

b = randi(2,length(a),1); %generation of random value ∈ [1,2]
b(a(:,2)==1) = 1; %if a(:,2) = 1 b = 1;

a = [a,b]
0
votes
A= [1  1
2  1
1  1
4  2
5  2
6  2
7  1
8  1
9  2
10  2
11  2] ;
colLength = length (A(:,1)) ;
thridcol = randi (2,colLength,1) 
A(:,3) = thridcol ;

flag = 1 ;
i = 1 ; ;
if ( sum (A(3,:) == 1) == length (A(2,:)))
    while (flag && i < colLength)
        A(3+i,3 ) = 1 ;          
        if (sum (A(3+i,:) == 2) == length (A(3+i,:)))
            flag = 0 ;
        end
          i = i +1 ;
    end
end