Invorrect number of answers

1 view (last 30 days)
Sarah Kneer
Sarah Kneer on 23 Dec 2020
Commented: Image Analyst on 23 Dec 2020
For this script I'm meant to use each value of d - 3 values - with each value of h - 24 answers - hence I should have 72 answers, but I only have 24 answers. Please help:
phi = 53;
h = 1/24:1/24:1;
d = 100:100:365;
for i = 1:1:length(d)
delta(i) = -23.45 * cosd((360/365) * (d(i)+10));
for j = 1:1:length(h)
h_a(j) = 360 * (h(j)-0.5);
alpha(j) = asind(((sind(phi) * sind(delta(i))) + (cosd(phi) * cosd(delta(i)) * cosd(h_a(j)))));
theta(j) = 90 - alpha(j);
end
if h <= 0.5
beta(j) = -acosd((((sind(delta(i)) * cosd(phi)) - (cosd(h_a(j)) * cosd(delta(i)) * sind(phi)))/sind(theta(j))));
else
beta(j) = acosd((((sind(delta(i)) * cosd(phi)) - (cosd(h_a(j)) * cosd(delta(i)) * sind(phi)))/sind(theta(j))));
end
end

Answers (2)

Walter Roberson
Walter Roberson on 23 Dec 2020
After your for for j loop, which ends before the if, j will have a value that is the last value assigned to it in the loop; for j=1:1:length(h) will leave j=length(h) after the loop. That is a single value, 24, so you are always writing to beta(24) so you are only ever getting one answer.
You should move the assignment inside the for loop, and you should assign to beta(i,j)
  2 Comments
Sarah Kneer
Sarah Kneer on 23 Dec 2020
Okay, now it’s working, thank you very much
Image Analyst
Image Analyst on 23 Dec 2020
Can you please "Accept" an anwer, and/or Vote for them, to give those who helped you "reputation points"? Thanks in advance.

Sign in to comment.


Cris LaPierre
Cris LaPierre on 23 Dec 2020
You are only capturing 1/3 of your data, then. This is because your outer for loop is always overwriting the previous result. This leaves you with just the values calculated in the last loop only.
To see how to capture all values, look at this example from the documentation.
Also, your if statement will always be false with the given criteria. This is because h is a vector, and the result of your conditional is mixed (~half true, half false). Perhaps you meant to include this inside your inner for loop? That would make more sense, since you index beta using your loop counter j. For your conditional, use h(j).

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!