MATLAB: Help with for loop.

for loopif statement

Hi, I have a for loop where d is a 100×1 array and d0 is the average value of the elements in d. I would like to know how I can change it so after each iteration I have a 100×1 result in final_table and after all iterations are completed the variable final_table is a 100×100 array. The way I have implemented the if loop is incorrect since I finish with a 50×100 array. What I am trying to implement is to go through the different values of d, if less than the average d0 then calculate final (variables final_N1 and final_No) to hopefully finish with a 100×1 result and repeat 100 times to finish with 100×100 array in final_table. Thanks.
for cnt=1:100
if d(cnt)<=d0
No=sum(d<=d0);
d_pos_No=find(d<=d0);
d_pos_No=d(d_pos_No);
final_No=d_pos_No/No;
final_N1=zeros(size(final_No));
else
N1=sum(d>d0);
d_pos_N1=find(d>d0);
d_pos_N1=d(d_pos_N1);
final_N1=d_pos_N1/No;
final_No=zeros(size(final_N1));
end
final_table(1:numel(final_No+final_N1),cnt)=final_No+final_N1;
end

Best Answer

OK, that's enough to figure out that the iteration isn't somehow dependent upon what did the first but the data are independent. There's no need for loops over the vectors; use Matlab's logical addressing features--for each column the calculation is simply
idx=d(:,icol)<=mean(d(:,icol)); % the logical index for the column
res(idx,icol)=d(idx,icol)/sum(d(idx,icol)); % the locations <= are true
idx=~idx; % the > locations are the logical negation
res(idx,icol)=d(idx,icol)/sum(d(idx,icol)); % set those
The above is in a loop over
icol=1:length(d)
the number of columns in the original array. The total of idx and ~idx includes every row so the length is the same. It will make a little speedup overall if you were to preallocate the res array as
res=zeros(length(d));
before beginning the loop if the array is quite large; otherwise it will be "growed" in size adding a column at a time.
Unless your other code is dependent upon only building a single element at a time for the d vector/array, you really don't need explicit loops at all. If it is fully a case of generating a random table, then
N=5; % the end size desired
d=rand(5); % the array or values (random or otherwise generated from the previous code)
and you can write the above logic and use accumarray to build the final result.