2

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?

1
  • I guess you could use evalin, but I wouldn't recommend it. Commented Jan 15, 2012 at 2:01

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

Try:

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

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

1 Comment

I still don't see how to apply this function to several such matrices.

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.