Eliminate a for loop to increase speed

3 vues (au cours des 30 derniers jours)
Howard Wilton
Howard Wilton le 23 Nov 2022
Commenté : Howard Wilton le 25 Nov 2022
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.

Réponse acceptée

Jan
Jan le 23 Nov 2022
Modifié(e) : Jan le 23 Nov 2022
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 commentaires
Jan
Jan le 24 Nov 2022
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 le 25 Nov 2022
Thank you very much!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by