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

Stephen23
Stephen23 2022년 2월 5일
편집: Stephen23 2022년 2월 5일
"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:

댓글을 달려면 로그인하십시오.

 채택된 답변

KSSV
KSSV 2022년 2월 5일
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.

추가 답변 (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"

카테고리

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

제품

릴리스

R2020b

질문:

2022년 2월 5일

편집:

2022년 2월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by