How to access vector elements one by one and do some calculation?
1 回表示 (過去 30 日間)
古いコメントを表示
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
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.
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Linear 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!