How to change output in FOR Loop

조회 수: 3 (최근 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