Eliminate a for loop to increase speed
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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?
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
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!