views:

292

answers:

3

Suppose I have a function y(t,x) = exp(-t)*sin(x)

In Matlab, I define

t = [0: 0.5: 5];
x = [0: 0.1: 10*2*pi];
y = zeros(length(t), length(x)); % empty matrix init

Now, how do I define matrix y without using any loop, such that each element y(i,j) contains the value of desired function y at (t(i), x(j))? Below is how I did it using a for loop.

for i = 1:length(t)
    y(i,:) =  exp(-t(i)) .* sin(x);
end
+8  A: 

Your input vectors x is 1xN and t is 1xM, output matrix y is MxN. To vectorize the code both x and t must have the same dimension as y.

[x_,t_] = meshgrid(x,t);
y_ =  exp(-t_) .* sin(x_);

Your example is a simple 2D case. Function meshgrid() works also 3D. Sometimes you can not avoid the loop, in such cases, when your loop can go either 1:N or 1:M, choose the shortest one. Another function I use to prepare vector for vectorized equation (vector x matrix multiplication) is diag().

Mikhail
voila! thanks for such an elegant solution.
Aamir
+4  A: 

there is no need for meshgrid; simply use:

y = exp(-t(:)) * sin(x(:)');    %multiplies a column vector times a row vector.
shabbychef
+1 for a simple and elegant matrix-multiplication solution.
gnovice

related questions