Clear Filters
Clear Filters

Creating new rows in a matrix, where the elements of these rows have to be different from previous rows(same row cannot occur twice) Matlab

1 view (last 30 days)

Hi, I'm trying to write a code that generates a 3x2 matrix. Each row is generated using randperm(3,2). This means each row is generated as a vector with 2 unique integers with values between 1 and 3.

The problem is that I want each new row to be different than all the previous. For example, if one row is [1 3], none of the next two rows can be [1 3] or [3 1].

I tried writing a code that checks the sum AND the multiplied value of each newly created row (for example 1+3=4 and 1*3 = 3 using the above example). My idea is that the multiplied value and the sum value of each new generated row is compared to the multiplied value and sum value of every other row that comes before it. If any of these values are the same (which means we will get a repetition), we keep generating a new row using randperm(3,2) until a completely new row is obtained.

My question is: how can I do this comparison? My code checks each each row before one at a time, and "forgets" every other row that it previously checked. It does not take into consideration ALL the previous rows, instead it only iterates back one step at a time. I tried using something like parents(i:-1:1) instead of parents(i-k,1) etc but couldn't make it work.

parents=randperm(3,2);
for i=2:3
   parents=[parents; randperm(3,2)];      
   for k=1:i-1
        while prod(parents(i,:))==prod(parents(i-k,:)) && sum(parents(i,:))==sum(parents(i-k,:))
            parents(i,:)=randperm(3,2);
        end  
    end
    i=i+1;
end
parents

Thanks in advance!

Arian

Answers (1)

Image Analyst
Image Analyst on 4 Jan 2018
Simply use isequal().
row1 = whatever...
row2 = whatever...
if isequal(row1, row2)
% Rows are identical
else
% Rows are not identical.
end
Can you figure it out from here?
  1 Comment
Arian Abedin
Arian Abedin on 4 Jan 2018

I tried this now:

    parents=randperm(3,2);
    parents=[parents;randperm(3,2)]
    while isequal(parents(2,:),parents(1,:)) || isequal(flip(parents(2,:)),parents(1,:))
    parents(2,:)=randperm(3,2);
    end
    parents

which works for two rows (the 2nd row will correctly be adjusted compared to the 1st row). How can I extend this to an arbitrary number of rows though? For example, if I were to add third row now, how can I make it check and remember both the previous rows? Thanks

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!