MATLAB: How to add for loop in the code to get a table of result and plot it

for loopplottable

Hi;
My problem is that I want to have a table of result including the first coloumn is "R" (from 2 to 7) and the second one is "N_states" (for each "R" I should have a spesefic "N_states") and then plot the table. (Hint: the code (from line 3 to 11) generets just one "N_states" for one "R = 7" corectly but I want to have different "N_states" for different "R" and then plot "N_states" vers. "R")
This is my code:
for R = 2:7
%

%R = 7;
N_states = 0;
for nx = 1:R
for ny = 1:R
if ((nx.*nx + ny.*ny) <= R.*R)
N_states= N_states + 1;
end
end
end
%
R = R + 1;
end
T = table(R(:),N_states(:));
plot (T)

Best Answer

Yes, there are some problems with your for loop. But problems with density of states are fun!
Remember, that when you say "for R=2:7; ... end", matlab automatically increments R on every loop. You don't have to include R+1.
Also, you want to collect a table of R and N_states values, but you've only made scalar values which are getting over written on each iteration of the loop. You need to allocate an array for the R and N_states values before the loop. In this case since you're ultimately using a table, you can allocate a table.
R = (2:7)'; % allocate column vector R, integers 2,3,4..7
N_states = zeros(size(R)); % allocate N_states as zeros. This vector is the same shape as R
T = table(R,N_states); % create a table with these values
for m = 1:height(T) % loop through all the rows of T with index m
for nx = 1:T.R(m) % nx and ny range from 1 to R, the R specified by THIS row m of the table
for ny = 1:T.R(m) % are you sure you don't want to go from 0?
if ((nx.*nx + ny.*ny) <= T.R(m).*T.R(m))
T.N_states(m)= T.N_states(m) + 1; % increment this N_states in table
end
end
end
% No incrementing of R or m or nx, ny here.
end
% tables don't have an explicit plot function. Extract the vectors and plot like this:
plot(T.R,T.N_states)
Computationally there are much faster ways to solve this problem, but let me know how this feels to you.