MATLAB: How to use MESHGRID or NDGRID instead of multiple FOR-Loop

meshgridndgrid

Dear coder, Briefly, the program objective was to evaluate all possible constant pairs for a different set of condition. Since there are SIX constant, the current implementation required SIX nested FOR-loop. However, the code looks so messy.
for f_p_kdeA=s.p_kdeA
for f_p_kdeF=s.p_kdeF
for f_p_PrmSq00=s.p_PrmSq00
for f_p_PrmSq01=s.p_PrmSq01
for f_p_PrmSq10=s.p_PrmSq10
for f_p_PrmSq11=s.p_PrmSq11
s=eval_s(s);
end
end
end
end
end
end
Thus, I wonder how to make the following code to be more efficient by eliminating the FOR-loops. Thru some reading, using the NDGRID is a possible ways to make the code more efficient. However, I have limited knowledge on how to implement it. I really appreciate if someone can point out on how to do it.
The complete code is a below
[comb,s]=ini();
comb= eval_forLoop(comb,s);
result=array2table(comb);
result.Properties.VariableNames=s.HeaderName;
function [comb,s]=ini()
load('stt_table.mat')
data=table2array(stt_table);
[s.state.kde,s.state.prm,s.state.sq]=deal(data(:,1),data(:,2),data(:,3));
s.p_kdeA=0:0.5:1;
s.p_kdeF=0:0.5:1;
s.p_PrmSq00=0:0.5:1;
s.p_PrmSq01=0:0.5:1;
s.p_PrmSq10=0:0.5:1;
s.p_PrmSq11=0:0.5:1;
nRow=(numel(s.p_kdeA))*(numel(s.p_kdeF))*(numel(s.p_PrmSq00))*...
(numel(s.p_PrmSq01))*(numel(s.p_PrmSq10))*(numel(s.p_PrmSq11));
comb=nan(nRow,7);
end
function comb= eval_forLoop(comb,s)
c_d=1;
for f_p_kdeA=s.p_kdeA
for f_p_kdeF=s.p_kdeF
for f_p_PrmSq00=s.p_PrmSq00
for f_p_PrmSq01=s.p_PrmSq01
for f_p_PrmSq10=s.p_PrmSq10
for f_p_PrmSq11=s.p_PrmSq11
s.table1=[f_p_kdeA;f_p_kdeF];
s.table2=[f_p_PrmSq00;f_p_PrmSq01;f_p_PrmSq10;f_p_PrmSq11];
s=eval_s(s);
comb(c_d,:)= [s.avrge_aa;f_p_kdeA;f_p_kdeF;f_p_PrmSq00;...
f_p_PrmSq01; f_p_PrmSq10;f_p_PrmSq11];
c_d=c_d+1;
end
end
end
end
end
end
end
%

Best Answer

Credit to KSSV & Andrei Bobrov, their proposed idea lead to the solution below.
KSSV: His idea allow more flexibility for the spacing interval.
Andrei Bobrov: The end result of the a = [a{:}]; is what desired.
Proposed solution
s.p_kdeA=0:0.2:1;
s.p_kdeF=0:0.5:1;
s.p_PrmSq00=0:0.5:1;
s.p_PrmSq01=0:0.5:1;
s.p_PrmSq10=0:0.02:1;
s.p_PrmSq11=0:0.5:1;
S = struct2cell(s) ;
CpTable = cell(6,1);
[CpTable{end:-1:1}] = ndgrid(S{:}) ;
CpTable = cellfun(@(x)x(:),CpTable,'un',0);
CpTable = [CpTable{:}];
Related Question