rallen
rallen

Reputation: 323

Matlab loop over variables (beginner)

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

Answers (3)

ypnos
ypnos

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

Oli
Oli

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

carl
carl

Reputation: 50554

Try:

a = ones(2,2)
arrayfun(@(x) 2*x , a)

You can make the function (2*x) whatever you want.

Upvotes: 0

Related Questions