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

2 次查看(过去 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
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?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by