How make this code execute faster?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi, I'm just trying to figure out how to make this code faster:
N = size(X);
temp = 1:N;
S1 = temp(~ismember(temp,S));%this runs slow
M = X(S,S1); %this runs slos
m = min(M);
cost = sum(m);
X is a square matrix.
Given array of indexes S, I want to extract the submatrix M of S rows, and S1 columns, where S1 are the indexes which are not in S.
Hope I explained it well.
There is a way to achieve the same results faster ?
댓글 수: 2
채택된 답변
Adam Danz
2019년 6월 9일
편집: Adam Danz
2019년 6월 9일
Sidx = ismember(1:size(X,1),S);
M = X(Sidx,~Sidx);
cost = sum(min(M,[],1));
This versions is slightly faster. I ran your and my versions 100,000 times with X set as a 32x32 matrix and compared the median speeds. This version is 1.11 times faster (p<0.001, Wilcoxon Signed Rank test).
댓글 수: 2
Adam Danz
2019년 6월 9일
편집: Adam Danz
2019년 6월 9일
" but I'm not sure it is the same"
That's easy to check. Run both versions on the same inputs and compare the results. Spoiler alert: they are the same ;)
I ran you're new version vs my version 100,000 times and their difference in run time has a factor of 1.0 (meaning no difference).
추가 답변 (1개)
dpb
2019년 6월 9일
Try
S1 = setdiff(1:N;S));
What is the precise definition of "runs slow(ly)"? In what context and how have you deduced/concluded this is so?
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!