# Variables within other variables

3 Ansichten (letzte 30 Tage)
Joe Bennet am 2 Apr. 2021
Kommentiert: Stephen23 am 2 Apr. 2021
I have variables L1 through L15 in my script and i am wondering if it would be possible to represent thesevariables as 'Ln' where n independant variable, in a way that allows the computer to read 'L4' for instance. This would mean instead of changing L1 at all locations in my script i can just change the one 'n' value and it does the rest for me?
##### 2 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Stephen23 am 2 Apr. 2021
Putting your data into one vector/array would be a much better use of MATLAB. Then you could use basic, powerful, efficient MATLAB approaches to writing your code, such as vectorization and indexing.
Your current approach, with lots of numbered variables, forces you into writing complex, inefficient code.

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Image Analyst am 2 Apr. 2021
There are many options depending on what type of variables your L are. You could use a double array, a structure array, a table, or a cell array. For example, if the L are scalars, you could do
Ln = [L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, ;12, L13, L14, L15];
n = 9; % Whatever....
result = Ln(n)
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Sajid Afaque am 2 Apr. 2021
I am not clear with your question but with whatever i have understood is
you can have a single cellarray containg all the variables from L1 to L15.
you can access the cells using the required index .
try it might help
% example
L1 = 'dog';
L2 = 'cat';
L3 = 'fish';
% now storing these variables in a single cell array
Lgeneral{1} = L1;
Lgeneral{2} = L2;
Lgeneral{3} = L3;
%suppose you want to access now L2
accessed_L2 = Lgeneral{2} ;
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by