When do you use periods with operators?
318 views (last 30 days)
Show older comments
With normal calculations, do you need to have periods with your operators, such as multiplication and exponents? When plotting a function, do you need to have periods with the operators when setting the parameters like the -2*pi and 2*pi? Do you also need to add them if the operators are in the function like the cosine function? Overall I was wondering if not having the periods would affect my answers?
w = 2;
y = 5;
z = (y*w^3)/(w-y);
r = (3*w)/(2*y);
disp(z);
disp(r);
x = -2*pi:2*pi;
f = @(x) 10*cos(.4*pi*x);
figure(1);
stem(x,f(x));
2 Comments
Stephen23
on 26 Apr 2022
"Overall I was wondering if not having the periods would affect my answers?"
In general, yes.
"Do you also need to add them if the operators are in the function like the cosine function?"
Rather than guessing you can read the very short list of array/matrix operations here:
Rule of thumb: if you are doing linear algebra use matrix operations, otherwise use array operations.
Accepted Answer
KSSV
on 26 Apr 2022
If you are doing scalar operations, then periods are not needed.
a = rand ;
b = rand ;
a*b
a^b
If you are doing array operations, then periods are needed, as this is element by element operation.
a = rand(1,10) ;
b = rand(1,10) ;
a.*b
a.^b
a*b % error, as there is no period
5 Comments
Stephen23
on 26 Apr 2022
Edited: Stephen23
on 26 Apr 2022
"I guess I meant to say that if I was actually missing a period, then my code wouldn't run at all?"
And I already wrote the answer: no, whether an error is thrown depends on other factors, e.g. the array sizes.
It is certainly possible to write incorrect code that uses the wrong operator and does not throw an error. This is no different to any other operator: e.g. if you write SIN instead of COS the compiler cannot know if you wrote the wrong function. Only you can know this.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!