Reputation: 633
If I have vector [1,2,3,4]
,I hope to use a function f
into every element to get
[f(1),f(2),f(3),f(4)]
If I have a matrix mat
>> mat=magic(3)
mat =
8 1 6
3 5 7
4 9 2
I hope to get
f(8) f(1) f(6)
f(3) f(5) f(7)
f(4) f(9) f(2)
Is any simple method to do this in matlab?
Upvotes: 0
Views: 74
Reputation: 5822
Solution
Use MATLAB's arrayfun function as follows:
arrayfun(f,mat)
Example
mat = magic(3); %defines input
f = @(x) x.^2; %defines f (f is the square function)
arrayfun(f,mat); %applies f on mat
Results
mat =
8 1 6
3 5 7
4 9 2
arrayfun(f,mat)=
64 1 36
9 25 49
16 81 4
Upvotes: 1