When do you use periods with operators?

319 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2022-4-26
"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.

请先登录,再进行评论。

采纳的回答

KSSV
KSSV 2022-4-26
If you are doing scalar operations, then periods are not needed.
a = rand ;
b = rand ;
a*b
ans = 0.4718
a^b
ans = 0.5064
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
ans = 1×10
0.2173 0.4201 0.6403 0.0300 0.1515 0.0821 0.1452 0.0927 0.4840 0.0081
a.^b
ans = 1×10
0.6706 0.9953 0.8034 0.9692 0.9331 0.5162 0.9009 0.6347 0.9799 0.8983
a*b % error, as there is no period
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for
elementwise multiplication.
  5 个评论
Stephen23
Stephen23 2022-4-26
编辑:Stephen23 2022-4-26
"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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by