Optimization in Indexing: Consolidate all switch/if statements into a smaller For loop??
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2019-8-5
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 个评论
Walter Roberson
2019-8-6
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!