# Memory efficient vectorization of a for loop

2 views (last 30 days)
Haider Ali on 29 Mar 2020
Answered: darova on 29 Mar 2020
Hello all,
I have the following piece of code which generate a nxnxm logical matrix A at the end. A matrix contains a lot of zeros. Each nxn matrix contains n 1s and remaining 0s.
clc;
clear; close all;
n = 3;
M = 2*n;
No_of_switches_in_each_column = [2,3,3,2,2];
tic
Ns = sum(No_of_switches_in_each_column);
All_possible_switching_states = 2^Ns;
I = eye(6);
Qi = [1,3,5,2,4,6];
Map_s2c = I(Qi',:);
Map_c2s = I(:,Qi);
TT_4allpossible_switch_states = dec2bin(0:All_possible_switching_states-1); % Truth table for Ns switches
Sw = cell(1,Ns); % Cell to store state (bar or cross) matricess of Ns No of switches.
A = false([6 6 All_possible_switching_states]);
%//********************************************************************//
for i = 1:All_possible_switching_states
comb_i = TT_4allpossible_switch_states(i,:);
for n = 1:Ns
if(strcmp(comb_i(n),'0'))
Sw{n} = [1 0; 0 1];
else
Sw{n} = [0 1; 1 0];
end
end
S1 = Sw{1}; S2 = Sw{2}; S3 = Sw{3};
S4 = Sw{4}; S5 = Sw{5}; S6 = Sw{6};
S7 = Sw{7}; S8 = Sw{8}; S9 = Sw{9};
S10 = Sw{10}; S11 = Sw{11};
S12 = Sw{12};
C1 = logical([1 zeros(1,5);...
zeros(2,1) S1 zeros(2,3);...
zeros(2,3) S2 zeros(2,1);...
zeros(1,5) 1]);
C2 = logical([S3 zeros(2,4);...
zeros(2) S4 zeros(2);...
zeros(2,4) S5]);
C3 = logical([S6 zeros(2,4);...
zeros(2) S7 zeros(2);...
zeros(2,4) S8]);
C4 = logical([S9 zeros(2,4);...
zeros(1,2) 1 zeros(1,3);...
zeros(1,3) 1 zeros(1,2);...
zeros(2,4) S10]);
C5 = logical([1 zeros(1,5);...
zeros(2,1) S11 zeros(2,3);...
zeros(2,3) S12 zeros(2,1);...
zeros(1,5) 1]);
A(:,:,i) = logical(C1*C2*Map_s2c*C3*Map_c2s*C4*C5);
end
I want an efficient implementation of the above code in terms of memory (it fails for larger arrays - array exceeds maximum array size preference) and computations.
It would be desirable to not use for loop and cell arrays.
Thanks
##### 2 CommentsShowHide 1 older comment
Haider Ali on 29 Mar 2020
@darova, yes I have looked at sparse matrix. But only 2D sparse matrices are supported.
I was thinking of first removing the for loop and then go for sparse matrix.

darova on 29 Mar 2020
Store values manually like sparse
% preallocation?
irow = [];
icol = [];
iplane = [];
for i = 1:...
% do stuff
val = logical(C1*C2*Map_s2c*C3*Map_c2s*C4*C5);
if sum(val(:))
[ii,jj] = find(val);
irow = [irow; ii];
icol = [icol; jj];
iplane = [iplane; i+ii*0];
end
end

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2019b

### Community Treasure Hunt

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

Start Hunting!