Reputation: 323
I would like to apply a function to several variables. Is there a nice way to do this?
Like:
M = ones(2,2)
N = zeros(3,3)
M = M + 1
N = N + 1
Works but I would like do something of the sort:
M = ones(2,2)
N = zeros(3,3)
L = ?UnknownStructure?(M, N)
for i = 1:length(L)
L(i) = L(i) + 1
end
Or is there a better way entirely to apply a function to a set of variables?
Upvotes: 2
Views: 1139
Reputation: 52387
There is no such thing as references in Matlab, in a sense that you can have two different variable names pointing to the same matrix.
However, you can have an array of matrices.
L = { M, N };
for i = 1:length(L)
L{i} = L{i} + 1
end
I tested this code in Octave. However note: The source matrices M, N are unchanged by this.
Upvotes: 2
Reputation: 16065
You can use cells:
M = ones(2,2)
N = zeros(3,3)
L = {M, N};
funct=@(x) x+1;
L2=cellfun(funct, L, 'UniformOutput',false);
Upvotes: 4
Reputation: 50554
Try:
a = ones(2,2)
arrayfun(@(x) 2*x , a)
You can make the function (2*x
) whatever you want.
Upvotes: 0