How to write for or while loop along with indexing?

Hello Sirs
May I ask your guidance for my study please?
There are three data in my problem (1) months and (2) Demand (3) X for several years.
I need to specify the first X value as SWA and second X value as EWA and third value as HF.
In this sample excel file 2 years data is given. Thus, there will be two SWA, two EWA and two HF.
Then, I need to mulitply the every 12 months Demand data with specific SWA, EWA and HF.
First SWA value (0.0319) should mulitply the demand 1:12 and second SWA value (0.9873) should multiply the demand 13:24 and so on.
First EWA (0.5272) should mulitply with constant value K= 1000 and plus with demand 1:12. Similarly, second EWA (0.0028) should multiply with K=1000 and plus the demand data from 13:24.
%input
clear all;
data=xlsread('data.xlsx');
demand=data(1:24,2);
x=data(1:6,3);
K=1000;
% I used incrementing by 3 to get the SWA , EWA and HF index and value.
SWA_idx=[1:3:6]';SWA_x=x(SWA_idx);
EWA_idx=[2:3:6];EWAx=x(EWA_idx);
HF_idx=3:3:6;HF=x(HF_idx);
%I select demand indexing for months and multiply with relevant SWA value.
y1=demand(1:12).*SWA_x(1);
y2=demand(13:24).*SWA_x(2);
z1=demand(1:12)+K*EWAx(1);
z2=demand(13:24)+K*EWAx(2);
%Now, I have to change everything sentence manually and it is very painful task for many years.
% So I want to use for loop or while loop. But, I don't know how to do it and can you kindly guide me please?
% Thank you very much.

 采纳的回答

hello
I modified a bit your code so that it will generate y and z cell arrays whatever the number of years. No manual code modifications required
hope it helps
%input
clear all;
data=xlsread('data.xlsx');
[m,n] = size(data);
demand=data(1:m,2);
x=data(1:6,3);
K=1000;
% I used incrementing by 3 to get the SWA , EWA and HF index and value.
SWA_idx=[1:3:6]';SWA_x=x(SWA_idx);
EWA_idx=[2:3:6];EWAx=x(EWA_idx);
HF_idx=3:3:6;HF=x(HF_idx);
% %I select demand indexing for months and multiply with relevant SWA value.
% y1=demand(1:12).*SWA_x(1);
% y2=demand(13:24).*SWA_x(2);
% z1=demand(1:12)+K*EWAx(1);
% z2=demand(13:24)+K*EWAx(2);
% %Now, I have to change everything sentence manually and it is very painful task for many years.
% % So I want to use for loop or while loop. But, I don't know how to do it and can you kindly guide me please?
% % Thank you very much.
nb_of_years = fix(m/12);
for ck = 1:nb_of_years
y{ck} = demand((1:12)+(ck-1)*12).*SWA_x(ck);
z{ck} = demand((1:12)+(ck-1)*12)+K*EWAx(ck);
end

2 个评论

Hi Mathieu
Thank you very much for your guidance.
It is really nice and perfectly works for me.
Best regards,

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by