Eliminate a for loop to increase speed

3 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Jan
Jan il 23 Nov 2022
Modificato: Jan il 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 Commenti
Jan
Jan il 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 il 25 Nov 2022
Thank you very much!

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by