get ridoff "for loops" while defining matrices elements, incl. improvement and reference
1 次查看(过去 30 天)
显示 更早的评论
Hello Community,
is it possible to write a code which is faster than my version?
function D = Dp(N)
D = (zeros(N-1,N-1));
for i=1:N-1
for j=1:N-1
if i ~= j
D(i,j)= -.5 * sin(j*pi/N)^2/sin(i*pi/N)^2 *(-1)^(i+j)/(sin(pi*(i+j)/(2*N))*sin(pi*(i-j)/(2*N)));
else
D(i,j) = 3/2 * cos(pi*i/N)/sin(pi*i/N)^2;
end
end
end
end
the reference i should inplement is:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/481483/image.png)
my "optimized" version:
function D = Dp(N)
D = (zeros(N-1,N-1));
for i=1:N-1
for j=1:N-1
if i ~= j
D(i,j)= -.5 * sin(j*pi/N)^2/sin(i*pi/N)^2 *(-1)^(i+j)/(sin(pi*(i+j)/(2*N))*sin(pi*(i-j)/(2*N)));
else
end
end
end
D = D + diag(1.5 * cos(pi*(1:N-1)/N)./sin(pi*(1:N-1)/N).^2);
end
0 个评论
采纳的回答
Pranav Verma
2021-1-12
Hi Marko,
Since you want to initilialise each and every element of your matrix with a different value, you'll have to visit each element of the matrix in any case. You can try vectorising your code to remove the nested loops using meshgrid/ndgrid but this may not necessarily provide an improvement in performance (running time).
Below are some useful threads where the code has been vectorized to remove the nested loops:
PS: I tried to run your code using parfor but that deprecated the performance due to overhead.
Thanks
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!