2

as i said in topic name, i want to put variables of 3 arrays in a row of another array.
look: for example i have 3 arrays X1, X2, X3 that them variables are:

X1=[1 2 3];   
X2=[4 5 6];   
X3=[7 8 9];  

and another array Y is this look:

Y=zeros(3,3);   
0  0  0   
0  0  0   
0  0  0   

now i want randomize X1 in first row, X2 in second row and X3 in third row like this:

3  1  2   
4  6  5   
9  8  7  

many thanx :)

2 Answers 2

1

This is easier to do if your Xi row vectors are in a single array X.

EDIT: Thanks to LuisMendo for the optimization suggestion.

X = [X1;X2;X3];
[rows,cols] = size(X);
Y = zeros(rows,cols);

for i = 1:rows
    Y(i,randperm(cols)) = X(i,:);
end
Sign up to request clarification or add additional context in comments.

15 Comments

It would be interesting to know which is faster: Y(i,:) = x(randperm(size(X,2))) or Y(i,randperm(size(X,2))) = x
@LuisMendo Nice thinking. That's probably the faster method.
i have another question. X1=[1 2 3]; ==> the hour of start of exam X2=[1...n]; ===> the day start program X3=[1..n]; ===> these are courses code for each number in X2(day) we should have each number of X1. X1 1 2 3 1 2 3 ... X2 1 1 1 2 2 3 ... X3 no matter have i spoke clearly? :-s
@SajadKhammar In other words, you want to pick one element from X1, one element from X2, and one element from X3, and find all possible combinations?
@LuisMendo The suggestion you made does seem to be mildly faster based on some tests I did. More time was saved by combining the two lines in my loop into one, however.
|
1

Use randperm:

n = size(Y,2); %// number of columns
Y(1, randperm(n)) = X1;
Y(2, randperm(n)) = X2;
Y(3, randperm(n)) = X3;

3 Comments

it is correct thanx. im amateur in Matlab please explain 'size(Y,2)' and also randperm.
size(Y,2) is the number of columns of Y (more info about size function here). randperm(n) is a random permutation of the numbers 1, 2 , ..., n. See the link in my answer for more details about randperm.
i have another question. X1=[1 2 3]; ==> the hour of start of exam X2=[1...n]; ===> the day start program X3=[1..n]; ===> these are courses code for each number in X2(day) we should have each number of X1. X1 1 2 3 1 2 3 ... X2 1 1 1 2 2 3 ... X3 no matter have i spoke clearly? :-s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.