Create dynamic array by comparing the new incoming variable value

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.?

回答 (1 件)

Jan
Jan 2019 年 5 月 23 日
編集済み: Jan 2019 年 5 月 23 日

1 投票

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.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2018b

質問済み:

2019 年 5 月 22 日

編集済み:

Jan
2019 年 5 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by