MATLAB: Need help using a loop to find maximum

forloop

Here is my code so far:
%Finding the max N given z
clc; clear;
c = [2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3]; %example data set
N=length(c);
eta=4;
D=100;
for i = 1:N
q(i)=(D*(N-(1/eta)))^eta * ((1-(N-1)*eta)*c(i) + eta*(sum(c)-c(i)))/(sum(c)^(1+eta));
end
j=1;
for i = 1:N
if q(i) > 0
c_new(j)=c(i);
j=j+1;
end
end
N=length(c_new);
for i = 1:N
q_new(i)=(D*(N-(1/eta)))^eta * ((1-(N-1)*eta)*c_new(i) + eta*(sum(c_new)-c_new(i)))/(sum(c_new)^(1+eta));
end
So basically I am wanting to take a given data set, [c], run each variable in [c] through a function to produce a second dataset, [q]. If any value of q is negative, I want to get rid of those corresponding entries in [c], run [c] again through the function and get a new set of values in [q]. I want to keep doing this iteration and check until there are no negative values in [q]. In the end I should have some value for N, the number of entries in [c].
I am a bit inexperienced with programming and not sure how to capture this concept and put it in Matlab.
Your help is much appreciated.

Best Answer

You are close. What you need is a while-loop. I've modified your code to make it work for this particular example data. It still has many potential problems, such as what if q never gets all positive? Also, there are many places that can be improved. Hope you can start from here and improve the code gradually.
%Finding the max N given z
clc; clear;
c = [2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3]; %example data set
eta=4;
D=100;
q_is_all_positive=false;
%
while ~q_is_all_positive
N=length(c);
for i = 1:N
q(i)=(D*(N-(1/eta)))^eta * ((1-(N-1)*eta)*c(i) + eta*(sum(c)-c(i)))/(sum(c)^(1+eta));
end
j=1;
q_is_all_positive=true;
for i = 1:N
if q(i) > 0
c_new(j)=c(i);
j=j+1;
else
q_is_all_positive=false;
end
end
c=c_new;
clear q c_new;
end
N=length(c)