Optimization in Indexing: Consolidate all switch/if statements into a smaller For loop??

1 vue (au cours des 30 derniers jours)
I have a few For statements that sort large amount of data into smaller matricies (B1 to B92)
Question: is it possible to consolidate a bunch of these switch/case statements into smaller or more efficient indexing code that will 'change' variable names from B1 to B2... B92 when applicable instead of using a switch/case scenerio? I hope this makes sense. I am trying to reduce the amount of lines I have to edit on repetative code, so that in the future it will be easier to modify / add additional features.
if Progress == (Data(Update+k,1))
Sensor = Progress;
switch Sensor
case 1
B1 = [B1 ;Data(Update+k,:)];
case 2
B2 = [B2 ;Data(Update+k,:)];
case 3
B3 = [B3 ;Data(Update+k,:)];
.
.
.
.
case 92
B92 = [B92 ;Data(Update+k,:)];
end
end

Réponse acceptée

Walter Roberson
Walter Roberson le 5 Août 2019
B = cell(92,1);
Then
B{Sensor}(end+1,:) = Data(Update+k,:);
No test needed, just the one statement.
If this is in a loop in which the entire update array is available then there are better ways available.
  3 commentaires
Walter Roberson
Walter Roberson le 6 Août 2019
If the matrix already exists, then you should look at splitapply() using Data(:,1) as the grouping variable. For example @(v) {v} can be a function that gathers all of the entries into one place. Or you could
B = cell(92,1);
for K = 1 : 92
mask = Data(:,1) == K;
B{K} = Data(mask, :);
end
Vadim Kachan
Vadim Kachan le 6 Août 2019
Thats awesome. Thank you Walter!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by