How can I save into an struct multiple arrays?

54 views (last 30 days)
Mariana
Mariana on 21 Feb 2020
Commented: Stephen23 on 24 Feb 2020
I have two variables. Id and Matrix.
Id : [0,1,2,3]
Matrix : 3600 x 9
I want to save in a structure the ID and the respective matrix.
For example:
ID Matrix
0 Matrix(1:900,:)
1 Matrix(901:1800,:)
2 Matrix(1801,2700:)
3 Matrix(2701:3600,:)
How can I make something like this in a matlab function in Simulink?

Answers (1)

Jalaj Gambhir
Jalaj Gambhir on 24 Feb 2020
Hi,
I understand you want to save numeric id’s as fields and sub matrices as values, in a struct, given a matrix and a double array of ids.
But the question is confusing in the sense that the representation that you have used seems to be of a table.
If what you want is a struct with fields as 0,1,2 and 3, then having numeric fields in a struct is not possible. You can have a look here, it states that the field for a struct must be a character array or a string scalar. However, you can convert the numeric array to a string array and have alternate representations of the elements as fields using matlab.lang.makeValidName using method followed in the following script:
function result = div(id, matrix)
start = 1;
string_ids = string(id);
valid_fields = matlab.lang.makeValidName(string_ids);
rows = size(matrix,1);
num_id = floor(rows/length(id));
result = struct;
for i = 1:length(id)-1
temp_array = matrix(start:start+num_id-1,:);
result.(valid_fields(i)) = temp_array;
start = start+num_id;
end
last_array = matrix(start:rows,:);
result.(valid_fields(length(id))) = last_array;
end
The above function outputs:
result = div(id,matrix);
result =
struct with fields:
x0: [900×9 double]
x1: [900×9 double]
x2: [900×9 double]
x3: [900×9 double]
If you want to store the result as a table, using the representation that you have mentioned in the question, you can use the following function:
function table_ans = div(id, matrix)
start = 1;
cell_id = num2cell(id');
rows = size(matrix,1);
num_id = floor(rows/length(id));
result = {};
for i = 1:length(id)-1
temp_array = matrix(start:start+num_id-1,:);
result{end+1} = temp_array;
start = start+num_id;
end
last_array = matrix(start:rows,:);
result{end+1} = last_array;
result = result';
table_ans = table(cell_id,result);
end
The above function outputs:
table_ans = div(id,matrix)
table_ans =
4×2 table
cell_id result
_______ ______________
[0] [900×9 double]
[1] [900×9 double]
[2] [900×9 double]
[3] [900×9 double]

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by