Is there a way to create a new variable inside a while loop?

5 visualizaciones (últimos 30 días)
Ryan Wilson
Ryan Wilson el 8 de Abr. de 2016
Editada: Stephen23 el 25 de Jun. de 2019
I am building a table that checks sets of time stamped data for continuity over specified time intervals.
One of my data sets has 96 subsets which would require 96 loops similar to LOOP 1.
What i would like to do is use a while loop nested inside a while loop functionally similar to loop 2. Is this possible?
%LOOP 1---------
CONTTABLE_170_2 = zeros(9,3);
CONTTABLE_170_2(:,1) = CONTTABLE(:,1);
CONTTABLE_170_2(:,2) = CONTTABLE(:,2);
SIZE_SORT_BIT_170_2 = size(SORT_BIT_170_2);
SIZE_SORT_BIT_170_2 = SIZE_SORT_BIT_170_2(1,1);
n=1;
while n<=9;
for i=1:SIZE_SORT_BIT_170_2;
TIMESTAMP = SORT_BIT_170_2(i,11);
TS_LIMIT_LOW = TIMETABLE(n,1);
TS_LIMIT_HIGH = TIMETABLE(n,2);
if and(TS_LIMIT_LOW<=TIMESTAMP, TS_LIMIT_HIGH>TIMESTAMP);
CONTTABLE_170_2(n,3) = 1;
else CONTTABLE_170_2(n,3) = 2;
end
end
n=n+1;
end
%LOOP 2-------------------
VARIABLE_VAL = 1;
while VARIABLE_VAL<=96;
CONTTABLE_170_[VARIABLE_VAL] = zeros(9,3);
CONTTABLE_170_[VARIABLE_VAL](:,1) = CONTTABLE(:,1);
CONTTABLE_170_[VARIABLE_VAL](:,2) = CONTTABLE(:,2);
SIZE_SORT_BIT_170_[VARIABLE_VAL] = size(SORT_BIT_170_[VARIABLE_VAL]);
SIZE_SORT_BIT_170_[VARIABLE_VAL] = SIZE_SORT_BIT_170_[VARIABLE_VAL](1,1);
n=1;
while n<=9;
for i=1:SIZE_SORT_BIT_170_[VARIABLE_VAL];
TIMESTAMP = SORT_BIT_170_[VARIABLE_VAL](i,11);
TS_LIMIT_LOW = TIMETABLE(n,1);
TS_LIMIT_HIGH = TIMETABLE(n,2);
if and(TS_LIMIT_LOW<=TIMESTAMP, TS_LIMIT_HIGH>TIMESTAMP);
CONTTABLE_170_[VARIABLE_VAL](n,3) = 1;
else CONTTABLE_170_[VARIABLE_VAL](n,3) = 2;
end
end
n=n+1;
end
end
  1 comentario
Stephen23
Stephen23 el 8 de Abr. de 2016
Editada: Stephen23 el 8 de Abr. de 2016
" Is this possible?"
Yes.
Should you do it ?
No.
As has been discussed a thousand times on this forum (and others), creating variables is a slow, buggy, and obfuscated way to write code.
The much faster, neater, and better way to achieve this is to use indexing and one variable. Really that is all, it is nothing complicated (unlike that hack code you would need to access multiple variables dynamically).
Read all of the links in my answer to know more about why dynamically accessing variable names is a bad idea.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 8 de Abr. de 2016
Editada: Stephen23 el 25 de Jun. de 2019

Más respuestas (0)

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by