Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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 Commenti
Adam Danz
Adam Danz il 7 Ago 2018
Modificato: Adam Danz il 7 Ago 2018
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 il 7 Ago 2018
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

Accedi per commentare.

Risposta accettata

OCDER
OCDER il 7 Ago 2018
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 Commenti
laith Farhan
laith Farhan il 7 Ago 2018
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?

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by