Azzera filtri
Azzera filtri

When do you use periods with operators?

319 visualizzazioni (ultimi 30 giorni)
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 Commenti
Stephen23
Stephen23 il 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.
Rafael Zapata
Rafael Zapata il 26 Apr 2022
Thank you for the extra resource.

Accedi per commentare.

Risposta accettata

KSSV
KSSV il 26 Apr 2022
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 Commenti
Stephen23
Stephen23 il 26 Apr 2022
Modificato: Stephen23 il 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.
Rafael Zapata
Rafael Zapata il 26 Apr 2022
Thank you for the clarification.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by