I am trying to write a MATLAB function which performs some calculations on a data set A. I want the function to return d (number of dimensions of A) matrices like A but with the jth column elements permuted:
A=[1,2,3 ; 7,8,9 ; 13,14,15]
perms_of_(A)
function perms = perms_of_(A)
[n,d]=size(A); % number of rows and columns
for j = 1:d % permute the elements of column j
A(:,j) = A(randperm(n),j)
end
end
I want matrices like:
A=[7,2,3 ; 1,8,9 ; 13,14,15]
A=[1,14,3 ; 7,2,9 ; 13,8,15]
A=[1,2,9 ; 7,8,3 ; 13,14,15]
But instead I get:
A=[7,2,3 ; 1,8,9 ; 13,14,15]
A=[7,14,3 ; 1,2,9 ; 13,8,15]
A=[7,14,15 ; 1,2,9 ; 13,8,3]
In other words, I want matrices exactly like the ORIGINAL matrix A but with JUST the jth column permuted. Somehow at the beginning of each iteration I need the matrix A to be reset to the original matrix defined outside the function. The permutations on column j-1,...,1 are appearing in output j (if my wording makes sense).
CodePudding user response:
I'm not sure I quite understand the question, but I think what you want to do is collect the d
permuted matrices in a cell array like so:
function perms = perms_of_(A)
[n,d] = size(A);
perms = cell(d,1);
for j = 1:d
perms{j} = A;
perms{j}(:,j) = A(randperm(n),j);
end
end
CodePudding user response:
You are not returning the result in your function. That is, you calculate a new A inside your function but you don't return it to the caller via the perms variable. Do something like this instead:
A=[1,2,3 ; 7,8,9 ; 13,14,15]
perms = perms_of_(A) % save the result of the call in a variable
function A = perms_of_(A) % declare the return variable to be A
[n,d]=size(A); % number of rows and columns
for j = 1:d % permute the elements of column j
A(:,j) = A(randperm(n),j);
end
end
This syntax of using the same variable name for input and output can sometimes result in inplace operations depending on how the function is called. If you don't use specific inplace operation syntax in the caller then a deep copy will be returned to the caller. E.g., calling the function like this inside another function will allow inplace operations:
function some_function
A=[1,2,3 ; 7,8,9 ; 13,14,15]
A = perms_of_(A) % save the result of the call in a variable
The above uses A for both input and output in the call to perms_of_( ), the function perms_of_( ) uses the same name variable for input and output, and the call to perms_of_( ) is made from within another function, so inplace operations can be done by MATLAB.