vectorization

2 次查看(过去 30 天)
Richard
Richard 2012-1-17
Can someone give me a push in the right direction regarding vectorising a loop. Is it possible to vectorise any loop? If so, I have the following script:
Names = fieldnames(Data);
for i = 1:length(fieldnames(Data));
for j = 1:length(Data.(Names{i}));
index = (Data.(Names{i}){j,1}(:, 1)==211);
Data.(Names{i}){j,1} = Data.(Names{i}){j,1}(index, :);%
end
end
Where 'Data' is a (1x3) structure. Although this particular loop doesn't take long to run, it seems like a good place to start to learn how to vectorise instead of using loops.
Any advice would be much appreciated.
  3 个评论
Sean de Wolski
Sean de Wolski 2012-1-17
I think you should describ ehow data is organized and how it's indexed. I think you might be able to simplify that which would in turn make vectorization easier.
Richard
Richard 2012-1-18
The structure 'Data' has 3 fields, called 'data1', 'data2', and 'data3' which are expressed by 'Names'. The index then goes through the first column in each matrix in 'Data.(Names)' to produce a matrix where only the rows which begin with 211 are kept.
I hope this is clearer.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2012-1-18
A simplification - please test if this is faster already, although it is not vectorized:
Names = fieldnames(Data);
for i = 1:length(fieldnames(Data));
Names_i = Data.(Names{i});
for j = 1:length(Names_i);
index = Names_i{j,1}(:, 1)==211;
Names_i{j,1} = Names_i{j,1}(index, :);
end
Data.(Names{i}) = Names_i;
end
If the cells stored in the field are {N x 1} cell vectors, omitting the second index saves time: Names_i{j} instead of Names_i{j,1}.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by