two variables with known values in equations; use loop in matlab

1 回表示 (過去 30 日間)
Norzuria Ibrahim
Norzuria Ibrahim 2015 年 9 月 29 日
コメント済み: Norzuria Ibrahim 2015 年 9 月 29 日
Hi I have question to ask. I have 3 variables with known variables, x, y, z.
x= 3, 1 , 4, 2, 1
y=3,4 ,5,1,1
z=2,2,1,2,2
I need to apply those variables in two related equations
d=x+y+2z
e=2d+xyz
how to solve this using loop
what I did
x=[3 1 4 2 1];
y=[3 4 5 1 1];
z=[2 2 1 2 2];
for i=1:length(x);
j=1:length(y);
k=1:length(z);
d=x(i)+y(j)+2*z(k)
d=d+1
e=2*d+(x(i)*y(j)*z(k))
end
did not work

採用された回答

Andrei Bobrov
Andrei Bobrov 2015 年 9 月 29 日
x=[3 1 4 2 1];
y=[3 4 5 1 1];
z=[2 2 1 2 2];
d=x+y+2*z;
e=2*d+x.*y.*z;
  4 件のコメント
Walter Roberson
Walter Roberson 2015 年 9 月 29 日
The code that Andrei provided does all of them at the same time. No loop is required.
Norzuria Ibrahim
Norzuria Ibrahim 2015 年 9 月 29 日
sorry.my mistake..you already told me how to wrote it above.anyway,thanks guys for your superb answers.

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

その他の回答 (1 件)

WAT
WAT 2015 年 9 月 29 日
編集済み: WAT 2015 年 9 月 29 日
It's a little unclear from your question, but if you mean you have 3 dependent variables (x,y,z) each observed at 5 different values of some independent variable (for example, x(t),y(t) and z(t)), and you want the values of c and e at those same times, then all you need to do is
d=x+y+2*z
e=2*d+x.*y.*z
The decimal in front of the multiply tells MATLAB to do the multiplication componentwise, rather than matrix multiplication.
Unless you're required to use a loop (for a HW assignment), in which case it would be something like
d = zeros(1,5);
e = zeros(1,5);
for i = 1:5
d(i) = x(i) + y(i) + 2*z(i);
e(i) = 2*d(i) + x(i)*y(i)*z(i);
end
But you don't want to do it this way unless you're explicitly required to use a loop.
  1 件のコメント
Norzuria Ibrahim
Norzuria Ibrahim 2015 年 9 月 29 日
編集済み: Norzuria Ibrahim 2015 年 9 月 29 日
I think the code you wrote is right. But, the variables x, y and z have values like I wrote above. How to write the data of the variables in matlab and use loop?

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by