How to change output in FOR Loop

16 visualizaciones (últimos 30 días)
Finley Watson
Finley Watson el 10 de Mayo de 2021
Editada: Jan el 10 de Mayo de 2021
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

Respuestas (2)

KSSV
KSSV el 10 de Mayo de 2021
Editada: KSSV el 10 de Mayo de 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 comentarios
Finley Watson
Finley Watson el 10 de Mayo de 2021
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 el 10 de Mayo de 2021
You need not to use string janL....your value for janL is nothing but X(1). Go by indexing, not by string.

Iniciar sesión para comentar.


Jan
Jan el 10 de Mayo de 2021
Editada: Jan el 10 de Mayo de 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", ...

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by