tags:

views:

49

answers:

1

I need this section of my code to run faster, as it is called many many times. I am new to Matlab and I feel as though there MUST be a way to do this that is not so round-about. Any help you could give on how to improve the speed of what I have or other functions to look into that would help me perform this task would be appreciated.

(Task is to get only lines of "alldata" where the first column is in the set of "minuteintervals" into "alldataMinutes". "minuteintervals" is just the minimum value of "alldata" column one increasing by twenty to the maximum of alldata.

minuteintervals= min(alldata(:,1)):20:max(alldata(:,1)); %20 second intervals
alldataMinutes= zeros(30000,4);
counter=1;
for x=1:length(alldata)
    if ismember(alldata(x,1), minuteintervals)
        alldataMinutes(counter,:)= alldata(x,:);
        counter= counter+1;
    end
end
 alldataMinutes(counter:length(alldataMinutes),:)= [];
A: 

This should give you what you want, and it should be substantially faster:

minuteintervals = min(alldata(:,1)):20:max(alldata(:,1));  %# Interval set
index = ismember(alldata(:,1),minuteintervals);  %# Logical index showing first
                                                 %#   column values in the set
alldataMinutes = alldata(index,:);  %# Extract the corresponding rows

This works by passing a vector of values to the function ISMEMBER, instead of passing values one at a time. The output index is a logical vector the same size as alldata(:,1), with a value of 1 (i.e. true) for elements of alldata(:,1) that are in the set minuteintervals, and a value of 0 (i.e. false) otherwise. You can then use logical indexing to easily extract the rows corresponding to the ones in index, placing them in alldataMinutes.

gnovice
using ISMEMBC (http://UndocumentedmMtlab.com/blog/ismembc-undocumented-helper-function/) should give an added performance boost over ISMEMBER. In this case the boost is negligible compared to that gained by gnovice's vectorization, but just FYI
Yair Altman
@Yair: Good to know, although there is a typo in your link. Here's the [correct link](http://undocumentedmatlab.com/blog/ismembc-undocumented-helper-function/) for anyone interested.
gnovice
thanks for pointing out gnovice :-)
Yair Altman

related questions