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

2 views (last 30 days)
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

Accepted Answer

Jess Lovering
Jess Lovering on 3 Oct 2019
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 Comment
Bryce Johnson
Bryce Johnson on 3 Oct 2019
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!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!