Eliminate a for loop to increase speed

3 ビュー (過去 30 日間)
Howard Wilton
Howard Wilton 2022 年 11 月 23 日
コメント済み: Howard Wilton 2022 年 11 月 25 日
I have a code snippet below which uses a for loop that I am trying to eliminate as I need to scale up to larger values of N and L.
clc; clearvars;
N = 2; L = 2; T = 1;
a = [1 1i; -1i -1];
nplq = int8(de2bi((0:2^(N*L)-1),'left-msb')); % [0 0 0 0; 0 0 0 1; 0 0 1 0; ... ; 1 1 1 1]
a_nl = zeros(2^(N*L),1);
for i = 1:2^(N*L)
a_nl(i) = a(nplq(i,1)+1,nplq(i,3)+1);
end
% wish i could do something like a_nl = a(nplq(:,1),nplq(:,3))
Any suggestions would be appreciated.

採用された回答

Jan
Jan 2022 年 11 月 23 日
編集済み: Jan 2022 年 11 月 23 日
N = 2; L = 2; T = 1;
a = [1 1i; -1i -1];
nplq = int8(de2bi((0:2^(N*L)-1),'left-msb')); % [0 0 0 0; 0 0 0 1; 0 0 1 0; ... ; 1 1 1 1]
a_nl = zeros(2^(N*L),1);
for i = 1:2^(N*L)
a_nl(i) = a(nplq(i,1) + 1, nplq(i,3) + 1);
end
% Without a loop:
a_nl2 = a(sub2ind(size(a), nplq(:,1) + 1, nplq(:,3) + 1));
isequal(a_nl, a_nl2) % Same result?
ans = logical
1
Do you really need the complete nplq matrix or are the 2 columns enough?
N = 2; L = 2;
M = 2^(N*L - 1)
v = uint8(1:2).';
nplq1 = repelem(v, M, 1);
c = 3 - 1; % 3rd column
nplq3 = repmat(repelem(v, M / 2^c, 1), 2^c, 1);
  3 件のコメント
Jan
Jan 2022 年 11 月 24 日
The creation of nplq can be expensive, if it exhausts the free memory: It is created as double at first, which needs 8 times the RAM of the needed UINT8 array. If this is a problem, you can try the C-mex function: FEX: VChoseKRO:
VChooseKRO_M(uint8([0,1]), N*L)
Howard Wilton
Howard Wilton 2022 年 11 月 25 日
Thank you very much!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by