How to change output in FOR Loop
17 views (last 30 days)
Show older comments
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
Answers (2)
KSSV
on 10 May 2021
Edited: KSSV
on 10 May 2021
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 Comments
KSSV
on 10 May 2021
You need not to use string janL....your value for janL is nothing but X(1). Go by indexing, not by string.
Jan
on 10 May 2021
Edited: Jan
on 10 May 2021
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", ...
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!