How to plug in values from for loop to a single formula?

Hey guys, I was wondering, how would I input 3 variables that have multiple values into one equation in matlab? I ran my variables through a for loop so they have multiple values for each point and I have stored my values from each of the for loops into a single variable x. For example:
When x=1, y=2, z=3
When x=2, y=3, z=4
When x=3, y=4, z=5
Formula: x^2+y^2+z^2

 Accepted Answer

I'm assuming you want the result for each set of inputs. Personally, I think the easiest way to do this is by putting the equation within the loop and indexing the results. Alternatively, I believe the following will work outside of the loop:
x = [1;2;3];
y = [2;3;4];
z = [3;4;5];
answer = x.^2+y.^2+z.^2;
The .^ symbols will cause each element of the x, y, and z arrays to be squared, rather than trying to square the entire matrix. Then, with all matrix math, addition applies straight across. Your answer then should be a 3x1 array of [14; 29; 50].

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2018b

Community Treasure Hunt

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

Start Hunting!