MATLAB Answers


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

Asked by Ethan Wilson on 6 Feb 2018
Latest activity Answered by John D'Errico
on 6 Feb 2018

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?


Sign in to comment.


2 Answers

Answer by Walter Roberson
on 6 Feb 2018

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()


Sign in to comment.

Answer by John D'Errico
on 6 Feb 2018

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));


Sign in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today