how use c++ in MATLAB to run 'for' loops

3 views (last 30 days)
mary khaliji
mary khaliji on 9 Aug 2015
Commented: Walter Roberson on 9 Aug 2015
Hello every body. I have a nested for loop that get long time to process, so I want to run the loop on my matrix by C++ and after execution,use from result. How I can do that?
for k=1:length(total_frames)
for j=1:length(all_SVs_in_template)
current_frame2(current_frame2==all_SVs_in_template(j))=l;
end
end
  1 Comment
Walter Roberson
Walter Roberson on 9 Aug 2015
Why are you doing the same test over and over again? Your nested loop does not involve k so the results are going to be the same each time.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 9 Aug 2015
Have you considered using
for k=1:length(total_frames)
current_frame2(ismember(current_frame2,all_SVs_in_template))=l;
end
  3 Comments
Image Analyst
Image Analyst on 9 Aug 2015
You probably need the coder or compiler product to convert that MATLAB code into C code or a DLL. Or just make it in C++ directly using Visual Studio.
Walter Roberson
Walter Roberson on 9 Aug 2015
In your code, each element of current_frame2 that is equal to all_SVs_in_template(1) is set to l. Then each element of current_frame2 that is equal to all_SVs_in_template(2) is set to the same value, l. Then each element of current_frame2 that is equal to all_SVs_in_template(3) is set to the same value, l.
A few seconds thought shows us that each element of current_frame2 that is equal to any value in all_SVs_in_template is set to the same value, l.
A way to test whether a value is equal to any of a list of values is to use ismember(). For example,
ismember(17, [8 17 3 4 3 11])
returns true because the initial value 17 appears somewhere in the list [8 17 3 4 3 11]. And your code only cares that each value in current_frame2 is somewhere in the list all_SVs_in_template in order to know that it should set the value to l.
ismember() also works with arrays in the first parameter, and returns a logical array of the same size, true where the particular element appears somewhere in the list that is the second element. So with simple logical indexing,
current_frame2(ismember(current_frame2,all_SVs_in_template))=l;
does everything at the same time.
And then your "for k" loop causes the same tests to be done length(total_frames) times, with exactly the same result each time, since nothing in the inner loop depended upon "k".
If your "l" in your inner loop is intended to be "k" then whether the extra loops are useful depends upon whether the values 1 : length(total_frames) appear in the values in all_SVs_in_template: in that situation, the result would be the same as executing once with k being the single largest value in 1 : length(total_frames) that appears in all_SVs_in_template.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!