assigning file from the struct

Hi,
I am looking for a some help in reading the file from teh sturct.
Fo example, I have sturct files named 'A' , 'B' , 'C' ,'D' etc. and inside each struct file I have many arrays stored (e.g. X, Y, Z,) inside teh struct file A.
Now, to call array 'X' from the each struct file I am using A.X; B.X; C.X; D.X. Though this is working fine and in my code everytime I have to change X and Y manually wherever thats been called. Is there any aletrnative way, essentially I am looking for something like
S = X;
A.S
B.S
C.S
D.S

3 Comments

What do you call "struct file"? Do you mean MAT files containing the struct? Did you import the data using data=load('A.mat') already?
It's in the form of 1x1 struct
Stephen23
Stephen23 on 14 Dec 2022
Edited: Stephen23 on 14 Dec 2022
"I have sturct files named 'A' , 'B' , 'C' ,'D' etc."
A file is some data saved on a storage device (e.g. hard-drive): https://en.wikipedia.org/wiki/Computer_file
A structure is a data class used in MATLAB memory: https://www.mathworks.com/help/matlab/structures.html
What is a "struct file" ? I have never heard of such a thing, nor is it clear how such a thing would even exist, or be used.

Sign in to comment.

 Accepted Answer

S = 'X';
A.(S)
B.(S)
C.(S)
D.(S)
This is called "dynamic field names".

3 Comments

Thank, Jan.
Just another quick question
Lets say
T1 = A_60.X;
T2 = A_60.X1;
T3 = A_60.X2;
In the above example is it possible to define variable instead of number 60. For e.g if I have number 60 stored in some variable C, is it possible to use like this
T1 = A_C.X;
T2 = A_C.X1;
T3 = A_C.X2;
Stephen23
Stephen23 on 14 Dec 2022
Edited: Stephen23 on 14 Dec 2022
"e.g if I have number 60 stored in some variable C, is it possible to use like this"
It is certainly possible, if you want to force yourself into writing slow, complex, inefficient, obfuscated, insecure, buggy code that is hard to debug:
Best avoided.
Use indexing, just like MATLAB is designed for.
@Turbulence Analysis: Stephen23 hits the point. Read and consider the linked tutorial carefully.
T3 = A_60.X2 looks like you have hidden the indices 3, 60 and 2 in the names of the variables or fields. This makes it much harder to access the fields, while using real indices is trivial:
T(3) = A(60).X(2)

Sign in to comment.

More Answers (0)

Categories

Asked:

on 14 Dec 2022

Edited:

on 14 Dec 2022

Community Treasure Hunt

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

Start Hunting!