How do I put multiple outputs of a function into separate variables

clear;clc;
v0= 180;
theta = [0,30,60,75]
v0y = v0.*sind(theta)
v0x = v0.*cosd(theta)
g = -9.81;
A = (0.5*g);
B = v0y;
C = 150;
eqn = [A B C]
t1 = ((-B)+((B.^2-4*A*C)).^0.5)/(2*A)
t2 = ((-B)-((B.^2-4*A*C)).^0.5)/(2*A)
The variable t2 has 4 outputs, for each value of theta. How can I make it so that each output is assigned to its new separate variable
I thought this would work below, but I guess im not sure I understand how matlab works. The error it gave me was "too many output arguments"
[theta1 theta2 theta3 theta4] = ((-B)-((B.^2-4*A*C)).^0.5)/(2*A)

1 Comment

"How do I put multiple outputs of a function into separate variables"
Why do you want to do that? Your data are already conveniently in one matrix, and matrices are what MATLAB is designed to work with (the name MATLAB comes from MATrix LABoratory), so why would you want to split up a perfectly good matrix into harder-to-work-with numbered variables? Numbered variables are usually a sign that a user is doing something wrong.
You can trivially access the elements of the matrix using indexing. Indexing is explained here:

Sign in to comment.

 Accepted Answer

It is unnecessary. You need not to do that. The code is already in the way you want.
t1 = ((-B)+((B.^2-4*A*C)).^0.5)/(2*A)
You can access it by t1(1), t1(2), t1(3), t1(4). Thats it; why you want to assign each element to a variable? Not required.

More Answers (1)

[theta1 theta2 theta3 theta4] = struct('result', num2cell(((-B)-((B.^2-4*A*C)).^0.5)/(2*A))).result{:};
You can use any valid matlab field name instead of using "result"

Products

Release

R2020b

Asked:

on 5 Feb 2022

Edited:

on 5 Feb 2022

Community Treasure Hunt

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

Start Hunting!