필터 지우기
필터 지우기

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

조회 수: 2 (최근 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 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