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!