repeat the code with different value each time

5 ビュー (過去 30 日間)
Az.Sa
Az.Sa 2023 年 3 月 5 日
コメント済み: Jan 2023 年 3 月 6 日
Hi
I have a matrix w= 6x222 . I have 37 window. I want to repeat the code with different w 37 times. First I use the the first 6 columns of w so I use W=w(:,[1:6]); and I have the results then I use the following 6 columns i.e.W=w(:,[7:12]); and so on untile I have the last 6 columns W=w(:,[217:222]);
How can I do this iteration and extract the 37 solutions from each W.
Thanks in advance

採用された回答

Jan
Jan 2023 年 3 月 5 日
編集済み: Jan 2023 年 3 月 5 日
w = rand(6, 222);
index = 1:6:size(w, 2);
result = zeros(1, numel(index));
for k = 1:numel(index)
aw = w(:, index(k):index(k)+5); % A 6x6 submatrix
result = yourCalculations(aw);
end
I'd avoid the names "w" and "W", because the letters can be confused easily.
A more Matlab'ish way:
ww = reshape(w, 6, 6, []);
Now the calculations might be applicable to the 3D array ww directly without a loop. See e.g. pagemldivide or pagemtimes.
  2 件のコメント
Az.Sa
Az.Sa 2023 年 3 月 5 日
編集済み: Az.Sa 2023 年 3 月 5 日
Thank you very much!
so if my code as follow
clear all
R=readtable('return.1.indexFeb.csv');
R=table2array(R);
w=readmatrix('window.opt.w.05.csv');
W=w(:,[1:6]);
gamma = 2;
Aeq = [1 1 1 1 1 1];
beq = 1;
lb = zeros(6,1);
ub = ones(6,1);
x0=0.1667*ones(1,6);
u = @(x) 1/(1-gamma)*x.^(1-gamma); % CRRA utility
obj = @(x)-sum(u(x*aw.'*R));
x = fmincon(obj,x0,[],[],Aeq,beq,lb,ub)
so I replace W=w(:,[1:6]) with
R=readtable('return.1.indexFeb.csv');
R=table2array(R);
w=readmatrix('window.opt.w.05.csv');
index = 1:6:size(w, 2);
result = zeros(1, numel(index));
for k = 1:numel(index)
aw = w(:, index(k):index(k)+5); % A 6x6 submatrix
gamma = 2;
Aeq = [1 1 1 1 1 1];
beq = 1;
lb = zeros(6,1);
ub = ones(6,1);
x0=0.1667*ones(1,6);
%x0=[.25,.25,.25,.25,0,0];
u = @(x) 1/(1-gamma)*x.^(1-gamma); % CRRA utility
% u = @(x) 1 - exp(-gamma *x);
obj = @(x)-sum(u(x*aw.'*R));
options = optimoptions(@fmincon,'Algorithm','sqp','MaxIterations',1500);
x = fmincon(obj,x0,[],[],Aeq,beq,lb,ub);
end
and this is will calculate my x values corresponding to the w 37 times, correct ?
how can I save the results so I can use it in a different step.
Jan
Jan 2023 年 3 月 6 日
for k = 1:numel(index)
...
x(k) = ...
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by