Sajad Khammar
Sajad Khammar

Reputation: 37

puting variables of an array in a row of another array in Matlab

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 :)

Upvotes: 2

Views: 54

Answers (2)

eigenchris
eigenchris

Reputation: 5821

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

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

Use randperm:

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

Upvotes: 1

Related Questions