Why I cannot run a function for each of the elements of a vector if the function calls the variable two times?

Hello, guys! I am new to Matlab, so take it slowly.
I wrote the following function of the "time" variable:
function A = x1(t)
%Ordinary differential equation solution
% x function of time
X=1;
fn=1;
phi=0;
wn=2*pi*fn;
xi=0.1;
A=X*exp(-xi*wn*t)*cos(sqrt(1-xi^2)*wn*t-phi);
end
And after that I declared the "time" vector:
t=1:0.001:10;
Now, I would like to define a vector with the values of the function for each vector element:
C=x1(t);
But Matlab doesn't like it and says:
Error using *
Inner matrix dimensions must agree.
Error in x1 (line 9) A=X*exp(-xi*wn*t)*cos(sqrt(1-xi^2)*wn*t-phi);
Error in Time (line 2) C=x1(t);
Can you explain me what I am doing wrong? Thank you!

 Accepted Answer

You need to use element-wise multiplication, not matrix multiplication (aka linear algebra):
A = X.*exp(-xi.*wn.*t).*cos(sqrt(1-xi^2).*wn.*t-phi);
Strictly speaking this is not required for the scalars, so this will also work:
A = X*exp(-xi*wn*t).*cos(sqrt(1-xi^2).*wn.*t-phi);
but it could be a good habit to use it everywhere that you do not wish to do matrix multiplication, in which case the first example is best.
For information on which operators have matrix and linear algebra versions, read this:

More Answers (0)

Categories

Asked:

on 10 Sep 2015

Edited:

on 10 Sep 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!