Vectorization of for loops with symbolic functions inside
조회 수: 2 (최근 30일)
이전 댓글 표시
Mohammad Zainullah Khan
2022년 5월 23일
댓글: Mohammad Zainullah Khan
2022년 5월 25일
Hi,
I have been using for-loops extensively and they served the prupose well until I had to run a code that requires over 140 thousand iteration. At that point my computer started taking an eternity to process it. So, I tried searching for ways to optimize the code and something I got introduced to is vectorization of the for-loops.
I have tried looking at ways to vectorize the two for loops but I can't seem to figure out a way that would suit my case. In my code, inside each iteration I am using symbolic variables and solving them for their values. Have a look at the simplified version of my code below:
syms t
vec1 = [5*cosd(t); 5*sind(t)];
vec2 = [t^2+2; t^3+5];
start_time = 0;
end_time = 360;
for time1 = start_time:1:end_time-1
for time2 = time1+1:1:end_time
A = double(subs(vec1, t, time1));
B = double(subs(vec2, t, time2));
syms x y %two unknowns
eq1 = transpose(A)*[x;y]
eq2 = transpose(B)*[x;y]
eq3 = [eq1; eq2];
solutions = solve(eq3,[x,y]);
%Output the solutions
x.solution
y.solution
end
end
Is there a way to vectorize the two time loops?
Thanks in advance for your help.
댓글 수: 0
채택된 답변
Walter Roberson
2022년 5월 23일
Yes, you can vectorize the code completely by just assigning 0 and 0 as the solutions.
You construct eq3 as the sum of two scalar terms each of which has x times something plus y times something. collect x and y to get something times x plus something times y. You solve the scalar sum for x and y (one equation with two unknown). But that has the trivial solution x=0 y=0 no matter what the details of the terms are.
댓글 수: 17
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Number Theory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!