avoiding nested for loops for matrix assignment

Hi,
I am a beginner to matlab. Can you please tell me how to avoid using nested for loops in matlab.
THis piece of code is taking lot of space in my hard drive and time.
for i = 1:10000
for j = 1:10000
a(i,j) = i+j
end
end

 採用された回答

KSSV
KSSV 2020 年 10 月 15 日
編集済み: KSSV 2020 年 10 月 15 日

0 投票

m = 10000 ; n = 10000 ;
[i,j] = meshgrid(1:n,1:m) ;
a = i+j ;

4 件のコメント

JAMMI ASHOK
JAMMI ASHOK 2020 年 10 月 15 日
Hi KSSV,
I am following your works on matlab. They are awesome.
Actually I doing a FEM assembly. How to assemble element matrices into global matrix, especially when system is large? Here i+j is only a sample operation - to see how much time matlab is taking - just for that. Assume here 'a' is my global matrix. If I have 10000 dofs - how can I do that operation without using loops.
Fortran does this in a flash, even python with numba is doing in a smaller time with loops. Should I shift to them or continue with matlab?
%example of a beam assembly
for idof = 10:16
for jdof = 10:16
a(idof,jdof) = a(idof,jdof) + e(idof,jdof)
end
end
%here dof is the element degree of freedom number
% a -> global stiffness matrix of size 10000 x 10000
% e is the element stiffness matrix - 6 x 6
KSSV
KSSV 2020 年 10 月 15 日
編集済み: KSSV 2020 年 10 月 15 日
Did you initialise it? If you don't initlaize it, MATLAB will take more time.. Also it should be possible without loop.
JAMMI ASHOK
JAMMI ASHOK 2020 年 10 月 15 日
Yes. If I am initializing it is improving the speed.
KSSV
KSSV 2020 年 10 月 15 日
If you are using a loop and filling the values into matrix......you must initilaize the matrix before loop.

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

その他の回答 (1 件)

Matt J
Matt J 2020 年 10 月 15 日
編集済み: Matt J 2020 年 10 月 15 日

0 投票

x = 1:10000;
a = x.' + x;

1 件のコメント

JAMMI ASHOK
JAMMI ASHOK 2020 年 10 月 15 日
Thanks Matt - it is working.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2020a

タグ

質問済み:

2020 年 10 月 15 日

コメント済み:

2020 年 10 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by