strcat(strings) to call a variable or matrix

I have a While loop that looks like this:
Zone1 = ...;
Zone2 = ...;
Zone3 = ...;
...
Zone9 = ...;
a = 1;
while a <= 9
TrueOrFalse = Subfunction(strcat('Zone',num2str(a)));
%Subfunction outputs 0 or 1
if TrueOrFalse == 0
break % end while loop
end % end if statement
a = a+1;
end % end while loop
Now, the problem I'm running into in Debug mode is that the strcat(strings) function is outputting a string that is correct, but it's not calling on the previously established variable or matrix.
What can I do to make that work?

 Respuesta aceptada

Cedric
Cedric el 30 de Abr. de 2014
Editada: Cedric el 30 de Abr. de 2014
You want to store your zone data in a numeric array or a cell array, and then index it for passing the relevant data item to the sub function.
For numeric data:
zonesData = [100, 800, 1750] ;
for k = 1 : length( zonesData )
isOk = SubFunction( zonesData(k) ) ;
if ~isOk
break ;
end
end
For other types of data, e.g. strings:
zonesData = {'USA', 'CH', 'FR'} ;
for k = 1 : length( zonesData )
isOk = SubFunction( zonesData{k} ) ;
if ~isOk
break ;
end
end

4 comentarios

David
David el 30 de Abr. de 2014
The Subfunction is intended to take an input numeric array, check the array for a certain condition, and output 1 (true) or 0 (false).
The issue is that, with the strcat(strings) function outputting a string ("Zone1" for example), the Subfunction is reading a string of characters "Zone1", instead of the numeric array "Zone1" that I established at the very beginning.
Cedric
Cedric el 30 de Abr. de 2014
Editada: Cedric el 30 de Abr. de 2014
My point is that we almost never build a series of variable names which contain an index, precisely because we cannot index them (hence your attempt to build the name by concatenation). Instead, we build arrays or cell arrays, which can be indexed. If your zone-specific arrays aren't vectors or are vectors with varying sizes, you can build a cell array of these arrays:
zonesData = cell( 9, 1 ) ; % Prealloc if you know in advance the size.
zonesData{1} = [1,4,3,2] ;
zonesData{2} = [8,7,3,2,4,9,1] ;
zonesData{3} = [4,9] ;
...
Then the loop
for k = 1 : length( zonesData )
isOk = SubFunction( zonesData{k} ) ;
if ~isOk
break ;
end
end
will pass each array to SubFunction. When k equals 3, for example, zonesData{k} is the content of cell #3 of zonesData, which is the array [4,9].
David
David el 30 de Abr. de 2014
This! This made everything possible. Thank you!
Cedric
Cedric el 30 de Abr. de 2014
My pleasure!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Preguntada:

el 30 de Abr. de 2014

Comentada:

el 30 de Abr. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by