Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a function of two variables without using any loop?

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
like image 562
Aamir Avatar asked Dec 25 '09 21:12

Aamir


1 Answers

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().

like image 142
Mikhail Poda Avatar answered Sep 20 '22 11:09

Mikhail Poda