Create dynamic array by comparing the new incoming variable value
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.?
0 Commenti
Risposte (1)
Jan
il 23 Mag 2019
Modificato: Jan
il 23 Mag 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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!