How to change output in FOR Loop

19 次查看(过去 30 天)
Finley Watson
Finley Watson 2021-5-10
编辑: Jan 2021-5-10
Hello All,
I am in need of assisstance as my lecturer doesn't seem to know how to do what I want.
So, I need to create a loop that will change the output variable depending on the loop iteration. Sounds confusing so I'll put the code in and how I imagine it works. Apologies if it isnt actually possible but Ive been told it should be, just she doesnt know how to do it herself !
JanL = find(DateVector(:,2) == 1)';
FebL = find(DateVector(:,2) == 2)';
MarL = find(DateVector(:,2) == 3)';
AprL = find(DateVector(:,2) == 4)';
MayL = find(DateVector(:,2) == 5)';
JunL = find(DateVector(:,2) == 6)';
JulL = find(DateVector(:,2) == 7)';
AugL = find(DateVector(:,2) == 8)';
SepL = find(DateVector(:,2) == 9)';
OctL = find(DateVector(:,2) == 10)';
NovL = find(DateVector(:,2) == 11)';
DecL = find(DateVector(:,2) == 12)';
This what I have currently and want to shrink it into a loop. In my mind it works something like this:
X = [JanL FebL MarL AprL MayL JunL JulL AugL SepL OctL NovL DecL]
for k = 1:1:12
X(k) = find(DateVector(:,2) == y)';
end
Therefore producing the variable JanL with the datevector data accordingly. Doesnt work and I have no ideas how to do this after some substantial looking and investigating.
Any help much appreciated Thanks

回答(2 个)

KSSV
KSSV 2021-5-10
编辑:KSSV 2021-5-10
X = zeros(12,1) ;
for k = 1:1:12
X(k) = find(DateVector(:,2) == k)';
end
The above is fine enough. You should go by indexing. X(1) means Jan, X(2) means Feb and so on....X(end) or X(12) means Dec. Read about indexing.
  4 个评论
Finley Watson
Finley Watson 2021-5-10
Done that as the X array contains what I need as variables, see 'JanL' etc. But it now sees JanL as an unrecognised function or variable.
KSSV
KSSV 2021-5-10
You need not to use string janL....your value for janL is nothing but X(1). Go by indexing, not by string.

请先登录,再进行评论。


Jan
Jan 2021-5-10
编辑:Jan 2021-5-10
Creating variables dynamically has a lot of severe disadvantaged. Using a struct is nicer, safer and more efficient.
X = {'JanL', 'FebL', 'MarL', 'AprL', 'MayL', 'JunL', ...
'JulL', 'AugL', 'SepL', 'OctL', 'NovL', 'DecL'};
Data = struct();
for k = 1:1:12
Data.(X{k}) = find(DateVector(:,2) == y)';
end
By the way, all of the variables end with L. Is this really useful? Maybe it is better to read, if you call the struct "L" and the fields "Jan", "Feb", ...

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by