How to access vector elements one by one and do some calculation?

1 回表示 (過去 30 日間)
laith Farhan
laith Farhan 2018 年 8 月 7 日
コメント済み: laith Farhan 2018 年 8 月 7 日
Dear all, I am facing problem with for loop, I have vector D has some values, the question is how to access these value one by one to do some calculation. I have done the below code but it does not work. Anyone could help me please.
p=2;
e1=0.5
c=10;
D= [0,0,100,0,39,0,0,55,0,7];
for g=1:length(D)
if (D(g)>50)
T1(g)=(e1*p) + c.*(D.^3);
end
if (D(g)<=50)
T2(g)=(e1*p) + c.*(D.^2);
end
end
T1=[0,0,10000001,0,0,0,0,1250001,0,0];
T2=[0,0,0,0,15211,0,0,0,0,491];
Re=(T1) + (T2);
The expected results: [0,0,10000001,0,15211,0,0,1250001,0,491];
  2 件のコメント
Adam Danz
Adam Danz 2018 年 8 月 7 日
編集済み: Adam Danz 2018 年 8 月 7 日
Your code breaks at this line
T2(g)=(e1*p) + c.*(D.^2);
The reason it breaks is because you're assigning a vector to a single index T2(g). Did you mean D(g)?
There are additional problems but we can start there.
In the future, if you want to improve your chances of getting help here, make sure your code is formatted properly and you specifically explain the problem you're having.
laith Farhan
laith Farhan 2018 年 8 月 7 日
Thanks Adam for helping me and sorry for the mistakes happened.
Regard to your solution, I have change D into D(g) but unfortunately the problem still valid. The length of T1 showed me less that D. At the end I need to do (T1+T2) but matrix dimension must agree.
p=2;
e1=0.5
c=10;
D= [0,0,100,0,39,0,0,55,0,7];
for g=1:length(D)
if (D(g)>50)
T1(g)=(e1*p) + c.*(D(g).^3);
end
if (D(g)<=50)
T2(g)=(e1*p) + c.*(D(g).^2);
end
end

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

採用された回答

OCDER
OCDER 2018 年 8 月 7 日
p = 2;
e1 = 0.5;
c = 10;
D = [0,0,100,0,39,0,0,55,0,7];
Re = zeros(size(D));
GT50Loc = D > 50; %Greater than 50 logical index
Re( GT50Loc) = e1*p + c*D( GT50Loc).^3; %Your "T1"
Re(~GT50Loc) = e1*p + c*D(~GT50Loc).^2; %Your "T2", but already added with you "T1".
Re =
1 1 10000001 1 15211 1 1 1663751 1 491
But the results are different from expected. Double check your expected values, or explain how you calculated them as the equation in the code you gave is ambiguous.
  3 件のコメント
laith Farhan
laith Farhan 2018 年 8 月 7 日
Dear OCDER and Adam,
Thanks for your reply. I need the for loop coz D value is changing every time. @OCDER: your code is not working with my simulation .
Please if anybody help me with my above code with for loop?
laith Farhan
laith Farhan 2018 年 8 月 7 日
Dear OCDER and Adam,
It works ...... thanks alot

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLinear Programming and Mixed-Integer Linear Programming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by