Let’s say I have a function, like:
function [result] = Square( x )
result = x * x;
end
And I have an array like the following,
x = 0:0.1:1;
I want to have an y array, which stores the squares of x‘s using my Square function. Sure, one way would be the following,
y = zeros(1,10);
for i = 1:10
y(i) = Square(x(i));
end
However, I guess there should be a more elegant way of doing it. I tried some of my insights and made some search, however couldn’t find any solution. Any suggestions?
For the example you give:
in which
.*and.^are the element-wise versions of*and^. This is the simplest, fastest way there is.More general:
which can be elegant, but it’s usually pretty slow compared to
I’d actually advise to stay away from
arrayfununtil profiling has showed that it is faster than a plain loop. Which will be seldom, if ever.In new Matlab versions (R2008 and up), the JIT accelerates loops so effectively that things like
arrayfunmight actually disappear in a future release.As an aside: note that I’ve used
iiinstead ofias the loop variable. In Matlab,iandjare built-in names for the imaginary unit. If you use it as a variable name, you’ll lose some performance due to the necessary name resolution required. Using anything other thaniorjwill prevent that.