How to solve an equation with a variable that has multiple values.

I have 5 values for x (x = 0, 15, 30, 55, and 85) and an equation with cos, say cos(x), and I need to find the answer for each of these values. Is there any way to do this while keeping one variable (x), or would I have to assign each value to a different variable?

답변 (2개)

x = [0, 15, 30, 55, 85];
y = cos(x);
Many functions such as cos() are vectorized, able to work on inputs of arbitrary sizes and shapes. Not all functions are vectorized, however, and for those you either have to loop or use a helper function such as arrayfun:
y = arrayfun(@cos, x);
By the way, those values look like degrees, and cos() expects radians. You would probably want to use cosd() instead of cos()
No need to do anything special like having a different variable for each case! Use a vector.
x = [0, 15, 30, 55, 85];
y = cosd(x)
y =
1 0.96593 0.86603 0.57358 0.087156
Note the use of cosd, since x is clearly in degrees.
The learning point is that MATLAB is a matrix language (vectors too.) Most such functions are vectorized, so that you can pass in a vector or array of values.
Of course, you could also have used a loop. But why? See the difference between just using MATLAB as it is intended, as a matrix language:
x = [0, 15, 30, 55, 85];
y = zeros(size(x));
for n = 1:numel(x)
y(n) = cosd(x(n));
end

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

질문:

2018년 2월 6일

답변:

2018년 2월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by