MATLAB Answers

modifying variable names to enable indexing in a loop

3 views (last 30 days)
Hi,
I am trying to access data within variables which have been named with their index as part of their name and want to access them in a ‘for’ loop with the loop index ‘k’ as part of the variable name ‘_Obj < k >’. Is there any way I can do this ?
Demo_data.Sensor_Obj0_VarX1.data
Demo_data.Sensor_Obj0_VarY1.data
Demo_data.Sensor_Obj0_VarX2.data
Demo_data.Sensor_Obj0_VarY2.data
etc . . . .
Demo_data.Sensor_Obj1_VarX1.data
Demo_data.Sensor_Obj1_VarY1.data
Demo_data.Sensor_Obj1_VarX2.data
Demo_data.Sensor_Obj1_VarY2.data
etc . . . .
Demo_data.Sensor_Obj2_VarX1.data
Demo_data.Sensor_Obj2_VarY1.data
Demo_data.Sensor_Obj2_VarX2.data
Demo_data.Sensor_Obj2_VarY2.data
etc . . . .

Accepted Answer

Bob Thompson
Bob Thompson on 27 Apr 2021
Edited: Bob Thompson on 27 Apr 2021
Adjust your variable to index into a multi-dimensional array. I recommend using the first dimension, rows, for the final number (x1, x2, x3, x4, etc.), the second dimension, columns, for x and y, and the third dimension, sheets, for the object number.
This does require that all objects contain the same number of x and y pairs.
Demo_data.Sensor(1,1,1).data
Demo_data.Sensor(1,2,1).data
Demo_data.Sensor(2,1,1).data
Demo_data.Sensor(2,2,1).data
etc . . . .
Demo_data.Sensor(1,1,2).data
Demo_data.Sensor(1,2,2).data
Demo_data.Sensor(2,1,2).data
Demo_data.Sensor(2,2,2).data
etc . . . .
Demo_data.Sensor(1,1,3).data
Demo_data.Sensor(1,2,3).data
Demo_data.Sensor(2,1,3).data
Demo_data.Sensor(2,2,3).data
Depending on the size, class, and consistency of data for each point, you might also be able to make the setup go to even more dimensions to encompass the data array indices. That would reduce one level of your structure, which will make it much easier to deal with.
  5 Comments
William Campbell
William Campbell on 27 Apr 2021
Hello Bob,
thanks again for your comments - I have just found out my problem : "Curly brackets" !
I didn't place curly brackets around the cell array in my structure in the lower loop !
and with some changes in indices within the script I now have a formatted dataset.
Thanks for all your comments - it has kept me engaged this evening for the last 5 hours and produced the right outcome. Thanks again.
radar(j).object(r).position = [ob1{r}.data(1,j); ob2{r}.data(1,j); ob3{r}.data(1,j)];

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!