Taking values from a Matrix and Inputting into an equation, using Loops

39 ビュー (過去 30 日間)
RS
RS 2020 年 7 月 23 日
コメント済み: Serhii Tetora 2020 年 7 月 23 日
Hello.
I have a matrix say: A = [1 2 3 4 5 6 7] and an eqaution y = x^2
I need to find a way to take each value of the matrix and input it into y in an automated way, say using For loops. I am also trying to do this by not making the resulting values of y as a matrix i.e. I just want the answer y gives for each value taken from a to be stored as a number and not a matrix.
I am a relative beginner to MATLAB and have no idea how to do this.
Any help greatly appreciated.

採用された回答

Serhii Tetora
Serhii Tetora 2020 年 7 月 23 日
A = [1 2 3 4 5 6 7];
for i = 1:length(A)
x = A(i);
y(i) = x^2;
end
y
  2 件のコメント
RS
RS 2020 年 7 月 23 日
This results in y = [1 4 9 16 25 36 49] which is a matrix
Is there any way I can take each of the answers of this matrix and store it as a different new variable using loops, for example:
Ans1 = 1
Ans2 = 4
Ans3 = 9
etc
Serhii Tetora
Serhii Tetora 2020 年 7 月 23 日
A = [1 2 3 4 5 6 7];
for i = 1:length(A)
x = A(i);
y(i) = x^2;
eval(sprintf('Ans%d = y(i)',i))
end

サインインしてコメントする。

その他の回答 (1 件)

William Alberg
William Alberg 2020 年 7 月 23 日
Hello Omar
If you want to replace "y" with one of the values in "A", you can do it the following way:
A = 1:7;
syms x y
eq = y == x^2;
for i = 1:length(A)
eq_temp = subs(eq, y, A(i))
end
If you want to calculate y, i would recommed doing it the following way, where "y = f(x)":
f(x) = x^2;
for i = 1:length(A)
val_temp = f(A(i))
end
  1 件のコメント
William Alberg
William Alberg 2020 年 7 月 23 日
I did not see Serhii's repley.
I also misunderstood, i thought you wanted the equation to be in symbolic format.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumber Theory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by