Looping command for vectors with common string prefix

조회 수: 19 (최근 30일)
Stefano Grillini
Stefano Grillini 2018년 8월 27일
편집: Stephen23 2018년 8월 30일
Dear all,
I need to iterate the same command for a list of vectors with common string prefix and a different number that characterise each. For instance, I have a market average "avilliq" and a list of vectors named milliq1, milliq2, ... , milliq91.
I need to run a MS_Regress_Fit and extract the parameters for each of these vectors. The code for one of them would be something like:
lnavilliq(isnan(lnavilliq))=[];
milliq1(isnan(milliq1))=[];
% Matrix of dependent vars
c = [lnavilliq milliq1];
dep= c; % Defines the dependent variables in system
constVec=ones(length(dep),1);
indep{1}=constVec;
indep{2}=[constVec lnavilliq];
S{1}=[1 1];
S{2}=[1 1 1];
k=2; % Number of states/regimes
[Spec_Out_1]=MS_Regress_Fit(dep,indep,k,S,advOpt);
% Extract vector of parameters (betas)
c_high=Spec_Out_1.param(9);
c_low=Spec_Out_1.param(10);
beta2_high = Spec_Out_1.param(11);
beta2_low = Spec_Out_1.param(12);
%Extracts transition matrix from parameter vector
beta2_p11=Spec_Out_1.Coeff.p(1);
beta2_p22=Spec_Out_1.Coeff.p(4);
I need to iterate Spec_out_# for each milliq# and then extract the parameters c_high_#, c_low_# and so on.
Any suggestion?
Thanks
SG
  댓글 수: 3
Stefano Grillini
Stefano Grillini 2018년 8월 30일
Thank you for your answer. While the drawbacks are clear to me now, I'm still a novice of Matlab. For example, I have imported my csv database as table into Matlab. In order to work with the arrays, I need to call them from the database as :
milliq1 = data.PortAvilliq1;
Since I have 25 arrays to use, I've tried:
numArrays = 25;
milliq = cell(numArrays,1);
for n = 1:numArrays
milliq{n} = data.PortAvilliq(n);
end
But this doesn't work. Where is the problem?
Thanks
Stephen23
Stephen23 2018년 8월 30일
편집: Stephen23 2018년 8월 30일
"Any suggestion?"
Do NOT do that. Magically accessing/defining variabel names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know more:
"Where is the problem?"
If the fieldname is PortAvilliq1, then your code will not magically add some number onto the end of the fieldname:
data.PortAvilliq(n)
What your code actually does is accesses n-th element of the field named PortAvilliq. Because this field (probably) does not exist you get an error. See my answer to know how to define the fieldname dynamically.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 8월 30일
편집: Stephen23 2018년 8월 30일
numArrays = 25;
milliq = cell(numArrays,1);
for n = 1:numArrays
fld = sprintf('PortAvilliq%d',n);
milliq{n} = data.(fld);
end
You should also read about fieldnames. Oh, and definitely avoid dynamically accessing any variable names.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by