problems with the step size in a for loop

4 views (last 30 days)
Dear readers,
I'm fairly new to Matlab so i beg your pardon for asking what will possible be a rather simple question:
First of all my code:
R=150;
h(1) = 0.6 ;
for i=1:2:10
Q(i) = sqrt(h(i)/R)
h(i+2) = -Q(i)*dT+h(i);
end
My problem is that when i look at the values of Q, it contains a lot of zeros. I realised that those must be values of the even i numbers ( Q(2), Q(4), Q(6) etc. ). My questions are: Why are those filled in as a zero, while i am not defining them at all. and how can i fix this? What i want is that the even i numbers do not have a Q value at all.
  1 Comment
Manoj
Manoj on 17 Nov 2014
I am not sure how you are calculating Q in the first place, because both h and R are single values. How do you want them to change in the loop to get an array of Q values ?

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 17 Nov 2014
When you assign a value to a matrix, using a non-existent index, matlab will automatically resize the matrix to that index and fill up all non-existent indices below with 0:
m = 6; %a 1x1 matrix, m(1) = 6
m(5) = 5; %resizes m to 1x5 matrix and fill missing values with 0
disp(m) %m(1) = 6, m(2:4) = 0, m(5) = 5
Therefore, when you assign a value to Q(3), it automatically assign a value of 0 to Q(2).
There's no concept of having no value at all in matrices.
You could instead put NaN (not a number) in your matrix:
Q(2:2:end) = NaN;
Or you could use cell arrays which can have empty elements
Q{i} = sqrt(h(i)/R)
Or simply rescale your indices to 1:5
for i=1:5
Q(i) = sqrt(h(i)/R)
h(i+1) = -Q(i)*dT+h(i);
end

More Answers (1)

Thorsten
Thorsten on 17 Nov 2014
Allocate Q to be a vector of 10 NaNs (not a number) before doing the computations
Q = nan(1,10);

Categories

Find more on Numeric Types 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!