How to generate a function of two variables without using any loop?
Solution 1
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()
.
Solution 2
there is no need for meshgrid
; simply use:
y = exp(-t(:)) * sin(x(:)'); %multiplies a column vector times a row vector.
Solution 3
Those might be helpful:
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html
http://www.mathworks.com/company/newsletters/digest/sept00/meshgrid.html
Good Luck.
Comments
-
Aamir almost 2 years
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