Greta Stein
Greta Stein

Reputation: 75

How to slice and store a set of curves in multiple variables in matlab?

I have a table with 2 columns (x and y value) and 100 rows (the x values repeat in a certain interval).

Set of linear functions

Therfore I would like to perform the following task for changeable table sizes (only changes in the row size!):

I want to determine the amount of repetitions of the x values and save this information as a variable named n. Here the amount of repetition is 5 (each x value occurs 5 times in total).

I want to know the range of the x values from repetition circle and save this information as R = height(range); Here the x range is [0,20]

With the above informaton I would like the create smaller tables where only one repetition of the x values is present

How could I implement this in matlab?

Stay safe and healthy,

Greta

Upvotes: 0

Views: 78

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4757

This approach converts the Table to an array/matrix using the table2array() function for further processing. To find the repeated pattern in the x-values the unique() function is used to retrieve the vector that is repeated multiple times. The range of the values can be calculated by using the min() and max() functions and concatenating the values in a 2 element array. The assignin() function can then be used to create a set of smaller tables that separate the y-values according to the x-value repetitions.

Table Used to Test Script:

x = repmat((1:20).',[5 1]);
y = rand(100,1);
Table = array2table([x y]);

Script:

Array = table2array(Table);
Unique_X_Values = unique(Array(:,1));

Number_Of_Repetitions = length(Array)/length(Unique_X_Values);

Range = [min(Array(:,1)) max(Array(:,1))];

Y_Reshaped = reshape(Array(:,2),[numel(Array(:,2))/Number_Of_Repetitions Number_Of_Repetitions]);

for Column_Index = 1: Number_Of_Repetitions
    Variable_Name = ['Small_Tables_' num2str(Column_Index)];
    assignin('base',Variable_Name,array2table(Y_Reshaped(:,Column_Index)));
    eval(Variable_Name);
end

fprintf("Number of repetitions: %d\n",Number_Of_Repetitions);
fprintf("Range: [%d,%d]\n",Range(1),Range(2));

Upvotes: 1

Related Questions