I want to change the "for loop" statement to a vectorizing code, but I've been stuck with this problem for many days, help!
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
I have heard that a vectorized version code is more efficient than a code written with " for-loop statement" when executing some math calculation, but I am not very familiar with Matlab's vectorized code writing style, is there any kind person willing to help to change the following code into a vectorized style code, or provide some tips for me, thank you very much !
Here is the mathmaetical expression that I want to calculate, denoted by sum1 and sum2
Here is Mycode
//c, h, g, e are all vector, here is their definition in my code.
c=zeros(q+1,1);
e=zeros(q+1,1);
h=zeros(q+1,1);
g=zeros(q+1,1);
....
// the part that i want to modify as vectorized code.
sum1=0;
sum2=0;
if(n>1)
for i=1:n-1
s=0;
for j=0:n-1-i
s=s+c(n-i-j+1)*(n-i-j)*h(j+1)-c(n-i-j)*h(j+2)*(j+1);
end
for j=0:n-i
s=s-h(n-i-j+1)*h(j+1)*i;
end
sum1=sum1+s*g(i+1);
end
for j=1:n-1
sum2=sum2+g(1)*(c(n-j+1)*(n-j)*h(j+1)-c(n-j)*h(j+2)*(j+1));
end
end
0 Commenti
Risposte (1)
Bhanu Prakash
il 13 Mag 2023
Hi Shelton,
As per my understanding, you want to vectorize "for" loop in the given code.
To vectorize the "for" loops in a given code, you can use the "coder.loop.vectorize" function. Consider the code shown below:
% creating a 10x1 matrix with random values
x=rand(10,1);
% creating a 10x1 zero matrix to store the output
y=zeros(10,1);
for i=1:length(x)
% vectorizing the "for" loop
coder.loop.vectorize
y(i)=sin(x(i));
end
The function "coder.loop.vectorize" is applied to the loop for calculating the output "y", resulting in a vectorized implementation.
For more information on the "coder.loop.vectorize" function, you can refer to the following documentation:
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!