Create dynamic array by comparing the new incoming variable value

2 views (last 30 days)
I am creating a dynamically allocated 2D array in which 1st column is the header column indicating the Step Number(a variable). I have to compare the incoming new value with all the Step Numbers i.e. 1st column and if I get a match assign that value to that column. If no matching column value is found, a new column with that value is created. Can anyone help me with this.?

Answers (1)

Jan
Jan on 23 May 2019
Edited: Jan on 23 May 2019
Letting an array grow dynamically consumes a lot of resources. For small arrays with 100 elements, the costs are not severe, but for larger arrays the exponentially growing effort is a DON'T for efficient code. But at least, it works:
A = zeros(0, 2);
for k = 1:1000;
StepNumber = randi(10);
m = find(A(:, 1) == StepNumber);
if isempty(m) % StepNumber not in the list yet
A(end+1, :) = [StepNumber, 1];
else
A(m, 2) = A(m, 2) + 1; % E.g. increase the counter
end
end
Of course this example could be implemented more efficiently, e.g.:
A = zeros(10, 2);
for k = 1:1000;
StepNumber = randi(10);
A(StepNumber, 2) = A(StepNumber, 2) + 1; % E.g. increase the counter
end
This avoids the growing of the array and searching in the list of formerly defined StepNumbers.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!