# if or elseif condition loop to replace values of an array

5 views (last 30 days)
Euan Muir on 15 Feb 2021
Answered: Walter Roberson on 15 Feb 2021
Hi, I need the following conditions to be met for:
• For solar time
• For the size of the array
• If month>2, year=year and month=month-3
• Otherwise, year=year-1 and month=month+8
I have the following lines of code. could you look over these calculations please? I am unsure if what I have is correct.
universalTime = datRawNREL.Hour + (datRawNREL.Minute/60) + (0/3600);
i=1
for i=1:105120
for solarTime = ((universalTime/24) + datRawNREL.Day + ((30.6*datRawNREL.Month)+0.5) + (365.25*(datRawNREL.Year - 1976)) - 8707.5)/36525
if datRawNREL.Month>2
datRawNREL.Year=datRawNREL.Year
datRawNREL.Month=datRawNREL.Month-3
elseif datRawNREL.Month<=2
datRawNREL.Year=datRawNREL.Year-1
datRawNREL.Month=datRawNREL.Month+9
i=i+1
end
end
end

Walter Roberson on 15 Feb 2021
No, you have a double nested loop, but nothing inside the first loop depends upon the loop control variable, so you are just repeating the same calculation 105120 times.
Nothing in your second loop or if statement depends upon the solar time.
Also, inside the inner loop you have
i=i+1
where i is the loop control variable. When you modify a loop control variable, the next time the loop is going to perform an interation, it changes the variable back, as if you had not changed the variable. The only time your change would make a difference is on the last iteration of the for i loop: it is not changed back on the last iteration. All that you are doing is outputing a series of very misleading i = values.
If you want to move on to the next iteration of i then use break in the inner loop. For example,
for i=1:105120
for solarTime = ((universalTime/24) + datRawNREL.Day + ((30.6*datRawNREL.Month)+0.5) + (365.25*(datRawNREL.Year - 1976)) - 8707.5)/36525
if datRawNREL.Month>2
datRawNREL.Year=datRawNREL.Year
datRawNREL.Month=datRawNREL.Month-3
elseif datRawNREL.Month<=2
datRawNREL.Year=datRawNREL.Year-1
datRawNREL.Month=datRawNREL.Month+9
break
end
end
end
break exits the inner-most for or while loop.

### 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!

Translated by