MATLAB Answers

improve this function in terms of speed

1 ビュー (過去 30 日間)
In my simulation this function is called many time and I would improve in terms of speed this function so I can earn in execution time this is the function
function [ruffled_head] = ruffle_head(head_rcv)
while 1
ruffled_head = head_rcv(randi(length(head_rcv));
if ruffled_head ~= 0
break;
end
end
end
this function receives a vector that is made of integer values and also zeros. it should return an integer value different from zero. I think that this function could be better.Any idea how to improve?

  1 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 13 日
why while 1?

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

採用された回答

Walter Roberson
Walter Roberson 2012 年 10 月 13 日
t = head_rcv(head_rcv ~= 0);
ruffled_head = t(randi(length(t)));

  1 件のコメント

Walter Roberson
Walter Roberson 2012 年 10 月 13 日
Note that this will not necessarily be faster than what you had. It depends on the length of the vector, and the occupation percentage. For a large matrix which is well populated, this version will be slower than what you have.

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 13 日
function [ruffled_head] = ruffle_head(head_rcv)
rufled_head=0;
while rufled_head==0
ruffled_head = head_rcv(randi(length(head_rcv)));
end

  0 件のコメント

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by