How do I use a for loop on ever element in an array?

조회 수: 1 (최근 30일)
Bryce Johnson
Bryce Johnson 2019년 10월 3일
댓글: Bryce Johnson 2019년 10월 3일
I need to use the if and elseif statements to modify the original values in the d array and spit out the new array according to the statements inside. Long story short how do I get an array back from a for loop? a needs to be the modified array.
d =([8 4 0.5 -3]);
for a = 1:length(d)
if d<0
d(a) = 2*cosd(d);
elseif d <= 0 & d <= 1
d(a) = 5*(d)^(1/3);
elseif d < 1 & d < 7
d(a) = ceiling(1/factorial(d));
elseif d >= 7
d(a) = 20*log(d)*(log10(d));
end
end

채택된 답변

Jess Lovering
Jess Lovering 2019년 10월 3일
I think that the below code is what you are asking about. Your if requirements seem like they may be off, however, so I changed those as well. And there is no function called "ceiling" but I put in ceil which is a rounding up command that you may be looking for.
d =([8 4 0.5 -3]);
for ii = 1:length(d)
if d(ii)<0
a(ii) = 2*cosd(d(ii));
elseif d(ii) >= 0 & d(ii) <= 1
a(ii) = 5*(d(ii))^(1/3);
elseif d(ii) > 1 & d(ii) < 7
a(ii) = ceil(1/factorial(d(ii)));
elseif d(ii) >= 7
a(ii) = 20*log(d(ii))*(log10(d(ii)));
end
end
  댓글 수: 1
Bryce Johnson
Bryce Johnson 2019년 10월 3일
Ah yes thank you very much that did solve it, it came up with the wrong answers but that was not your fault, I wrote the problem down wrong. You did help me get the function working though I appreatie that!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by