Converting a 2d array into a 3d array

15 ビュー (過去 30 日間)
Vinay Killamsetty
Vinay Killamsetty 2021 年 11 月 28 日
回答済み: Turlough Hughes 2021 年 11 月 28 日
Hi,
I am having a 2d array with size mxn
I want to convert each column into a seperate 2d diagonal matrix--- a total of 'n' diagonal matrices of size mxm
Then combining all the 2d diagonal matrices as a single 3d matrix.---size mxmxn
I tried to do this with employing a for-loop but it is taking lot of time
Can this be done without using a loop and at a faster speed?
  2 件のコメント
Turlough Hughes
Turlough Hughes 2021 年 11 月 28 日
Can you give an example of the code you have implemented?
Vinay Killamsetty
Vinay Killamsetty 2021 年 11 月 28 日
編集済み: Vinay Killamsetty 2021 年 11 月 28 日
size of Z_int is mxn
Z = nan(m,m,n)
for i = 1 : size( Z_int , 2)
Z( : , : , i ) = diag( (Z_int( :, i ) ) ;
end

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

回答 (2 件)

Chunru
Chunru 2021 年 11 月 28 日
"it is taking lot of time" for what size of array?
m=200; n=100;
Z_int = rand(m, n);
Z = nan(m,m,n);
tic
for i = 1 : size( Z_int , 2)
Z( : , : , i ) = diag( Z_int( :, i ) );
end
toc
Elapsed time is 0.009776 seconds.

Turlough Hughes
Turlough Hughes 2021 年 11 月 28 日
You could write a linear index for the diagonal elements as follows:
[m,n] = size(Z_int)
Z = zeros(m,m,n);
idx = repmat((1:m+1:m^2).',1,n) + m^2*(0:n-1);
Z(idx(:)) = Z_int(:)
This is 2-4x faster for m >= 400 on my computer (n=500), however, on the matlab servers its a slightly slower. Whether it's faster or not for you will depend on your hardware, the size of your arrays and probably the version of matlab that you're using too.

カテゴリ

Help Center および File ExchangeLinear Algebra についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by