How make this code execute faster?

1 回表示 (過去 30 日間)
Andrea Abbate
Andrea Abbate 2019 年 6 月 9 日
編集済み: Adam Danz 2019 年 6 月 9 日
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 件のコメント
madhan ravi
madhan ravi 2019 年 6 月 9 日
編集済み: madhan ravi 2019 年 6 月 9 日
What is size of X?
Andrea Abbate
Andrea Abbate 2019 年 6 月 9 日
編集済み: Andrea Abbate 2019 年 6 月 9 日
X is a square matrix, NxN, it is variable. What does you mean with size? I don't know which exact size will it be

サインインしてコメントする。

採用された回答

Adam Danz
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 件のコメント
Andrea Abbate
Andrea Abbate 2019 年 6 月 9 日
Thank you for your answer!
I tried using your suggestion and I came up to this:
S1 = ~ismember(1:size(X,1),S);
M = X(S,S1);
cost = sum(min(M,[],1));
Which seems to run even faster, but I'm not sure it is the same. The results seems to be good
Adam Danz
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
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?
  1 件のコメント
Andrea Abbate
Andrea Abbate 2019 年 6 月 9 日
編集済み: Andrea Abbate 2019 年 6 月 9 日
I used the profiler and that is the part of code that runs slower than the others.
However, I tried setdiff before, but it runs slower

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by