Optimization in Indexing: Consolidate all switch/if statements into a smaller For loop??
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Vadim Kachan
am 5 Aug. 2019
Kommentiert: Vadim Kachan
am 6 Aug. 2019
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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 5 Aug. 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 Kommentare
Walter Roberson
am 6 Aug. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!