When putting a variety of values in one at a time to an equation it outputs the right answer, but when I put in an array of values the answers are wrong

2 Ansichten (letzte 30 Tage)
I have an equation and a range of values I want to be input into said equation to then make a graph of. The output however gives me a range of y values that are the wrong answers and I can't work out why, but if I equate x to a single number I get the right output. The code looks like as follows:
x = -10:1:10
y = (cos(x)+tanh(x))/x+(x/100)

Akzeptierte Antwort

Paul
Paul am 15 Okt. 2021
If you want y to be evaluated for each element of x, you need to use the "element-wise" operator ./ (note the dot) instead of /.
x = -10:1:10
x = 1×21
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10
y = (cos(x)+tanh(x)) ./ x+(x ./ 100)
y = 1×21
0.0839 0.1223 0.0632 -0.0348 -0.0534 0.0932 0.3732 0.6317 0.6701 0.2113 Inf 1.3119 0.2939 0.0317 0.1264 0.3067 0.3867 0.3206 0.1868 0.0999 0.1161
Simlarly you'd need .* and .^ for element-wise muliplication and exponentiation. The bare / operator is called "mrdivide," which performs a matrix division. Start reading here and follow the documentation to learn more.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by