Extracting a banded matrix from a dense matrix in MATLAB - matlab

I have a large dense matrix, say matrix A of size 10000 by 10000 and I need to extract a banded matrix of bandwidth say 10 from it, i.e.,
B(i,j) = A(i,j) if |i-j| <=10
B(i,j) = 0 otherwise
What is the most efficient way to go about doing this in MATLAB?

I don't know that this is the most efficient way, but here is a way to create a matrix banded about the main diagonal via masking using the toeplitz() function:
r = zeros(1,size(A,2));
r(1 : ceil(bandwidth/2)) = 1;
bandedMask = toeplitz(r); %Create a banded toeplitz matrix of 1s and 0s
bandedMat = bandedMask.*A;
Note: This method assumes your bandwidth is odd.

As it is a huge matrix it might be a useful option not to copy it a second time to the memory. In that case
N = 10;
M = ...
for lin = 1:size(M,1)
M(lin, lin+N:end) = 0;
M(lin, 1:lin-N) = 0;
end
could be useful (depends whether you need the original matrix or not afterwards).
In the case you have to keep the original matrix you could think about representing your matrix diagonal by diagonal or as sparse matrix. In the case you have to copy the matrix you shouldn't touch all the elements that you don't need.
You should evaluate the different ways and tell us your results :-)

Suppose you have a matrix B and bandwidth n:
B = rand(16,7);
n = 4;
% Index main diagonal
szB = size(B);
idx = abs(bsxfun(#minus, (1:szB(1))',1:szB(2))) <= n;
% Build sparse
[r,c] = find(idx);
sparse(r,c,B(idx))

Related

Random numbers using rand() in matlab

I am using Matlab function round(rand(256)) to create a square matrix of size 256x256 with random distribution of 0s and 1s.
What I specifically want to do is that I want to somehow specify number of 1s that rand() (or any other relevant function for that matter) to generate and distribute throughout the matrix randomly
Magdrop’s answer is the most straight-forward method, it computes the percentile of the random values to determine the threshold.
Another two options involve randperm:
Randomly permute all indices into the matrix, then threshold:
sz = [256,256]; % matrix size
n = 256; % number of zeros
M = randperm(prod(sz)) <= n;
M = reshape(M,sz);
Randomly permute indices and select n as the locations of the ones:
indx = randperm(prod(sz),n);
M = zeros(sz);
M(indx) = 1;
You could also generate the random value the usual way, but before you round them, sort them as a vector. The number of 1s will the index in the sorted vector you want to cut for 1s or 0s. For example, let say we want 50 1s:
matrix = rand(256,256);
vec = sort(reshape(matrix,[],1));
thresh = vec(50);
matrix(matrix <= thresh) = 1;
matrix(matrix > thresh) = 0;
You could use the randi function to determine the locations of where to insert the ones, and then place those ones into your matrix. For example for n ones:
matrix = zeros(256,256);
onesIndices = randi([0 256*256],1,n);
matrix(onesIndices) = 1;
One problem with this approach is that randi can generate repeat values, though for this example, where the size of the matrix is large and the number of ones is low, this is pretty unlikely. You could test if this is the case and "reroll:" so if sum(sum(matrix)) is less than n you know you had a repeat value.
Edit: a better approach is to use randperm instead of randi and only take the first n elements. This should prevent there from being repeats and having to re-roll.

Vectorizing eigen value calculation of 3*3*N matrix in Matlab

Currently I am using the following code to obtain eigen values:
A = randi(100,3,3,4000000);
eig_vals = zeros(4000000,1);
for i =1:4000000
eig_vals(i) = max(eig(A(:,:,i))) ;
end
I need help to vectorize my eigen value calculations without using a for loop.
Thanks,
Prithivi
You can can calculate eigenvalues of a block-diagonal matrix composed of smaller [3 x 3] matrices:
C=mat2cell(A,3,3,ones(1,size(A,3)));
B=blkdiag(sparse(C{1}),C{2:end}); % A sparse block diagonal matrix
eig_vals = max(reshape(eig(B),3,[]),[],1);
But this may not be the most efficient one. So you can process the data part by part to reduce the time for creation of the sparse matrix:
s = 4000;
f = find(kron(speye(s),ones(3))); % indices for matrix blocks
B = spalloc(s*3,s*3,s*3*3); % preallocate the sparse matrix composed of 4000 matrices of size [3 x 3]
eig_vals = zeros(4000000,1);
for k = 0: 4000000/s-1
B(f)= A(:,:,k*s+1:k*s+s);
eig_vals(k*s+1:k*s+s) = max(reshape(eig(B),3,[]),[],1);
end
Here s=4000 is not the best chunk size. You can tune it for the best performance.

Fill a zeros matrix with specific numbers of 1

I'm facing a problem. I have a zeros matrix 600x600. I need to fill this matrix with 1080 1s randomly. Any suggestions?
Or, use the intrinsic routine randperm thusly:
A = zeros(600);
A(randperm(600^2,1080)) = 1;
A = sparse(600,600); %// set up your matrix
N=1080; %// number of desired ones
randindex = randi(600^2,N,1); %// get random locations for the ones
while numel(unique(randindex)) ~= numel(randindex)
randindex = randi(600^2,N,1); %// get new random locations for the ones
end
A(randindex) = 1; %// set the random locations to 1
This utilises randi to generate 1080 numbers randomly between 1 and 600^2, i.e. all possible locations in your vectors. The while loop is there in case it happens that one of the locations occurs twice, thus ending up with less than 1080 1.
The reason you can use a single index in this case for a matrix is because of linear indexing.
The big performance difference with respect to the other answers is that this initialises a sparse matrix, since 1080/600^2 = 0.3% is very sparse and will thus be faster. (Thanks to #Dev-iL)
This is one way to do it,
N = 1080; % Number of ones
M = zeros(600); % Create your matrix
a = rand(600^2,1); % generate a vector of randoms with the same length as the matrix
[~,asort] = sort(a); % Sorting will do uniform scrambling since uniform distribution is used
M(asort(1:N)) = 1; % Replace first N numbers with ones.

how to vectorze this kind of loop for array

I'm newbie to Matlab. I have some questions.
How can I vectorise this loop:
epsilon = 0.45;
t = -3.033;
n = 100;
I = ones(n,n);
%// diagonal block 1
DB1 = gallery('tridiag',ones(1,n-1),ones(1,n),ones(1,n-1));
for k = 1:n
DB1(k,k) = epsilon;
end
for k = 1:n-1
DB1(k,k+1) = t*heaviside((-1)^(k+1));
end
for k = 2:n
DB1(k,k-1) = t*heaviside((-1)^k);
and this loop with LRG, R2, R1 are 3D arrays
for k = 2:N
LRG(:,:,k) = inv(R(:,:,k) - R2(:,:,k-1)*LRG(:,:,k-1)*R1(:,:,k-1));
end
Is there any way to handle the third dimension of an array (page) without writing (:,:,...) many times?
You don't need to call gallery: this will just initialize DB1 to a specific sparse tridiagonal matrix, which you manually overwrite afterwards. With n=100, I suspect that you don't actually want to work on sparse matrices. Here's the solution:
epsilon = 0.45; t = -3.033;
n = 100;
DB1 = zeros(n); %initialize to 0
%diagonal indices
inds=sub2ind([n n],1:n,1:n);
DB1(inds) = epsilon;
%superdiagonal
inds=sub2ind([n n],1:n-1,2:n);
DB1(inds) = t*heaviside((-1).^(2:n));
%subdiagonal
inds=sub2ind([n n],2:n,1:n-1);
DB1(inds) = t*heaviside((-1).^(2:n));
Here sub2ind lets you compute linear indices from your matrix indices, allowing you to access "subvectors" in your matrix. Watch out for the exponentialization in the heaviside: you need .^ instead of ^ to perform an element-wise operation using the vector 2:n.
If you insist on getting a sparse matrix, you could either convert this matrix to sparse by calling
DB1=sparse(DB1);
which is the easiest option if your matrix is small. If n was larger and you would really need sparse matrices, then you could set up the sparse matrix itself by
DB1new=sparse([1:n 1:n-1 2:n],[1:n 2:n 1:n-1],...
[epsilon*ones(1,n) t*heaviside((-1).^(2:n)) t*heaviside((-1).^(2:n))],n,n);
This call sets the elements of DB1new one-by-one according to its vector arguments: it takes the first index from the first input argument, the seconf index from the second, and the corresponding element from the third vector (see help sparse in MATLAB).
As for your second question: I'm not sure I understand correctly. Like in my example, sub2ind can be used to transform the multidimensional indices into linear ones, see help sub2ind. But personally, I think using the array notation is far more transparent and less prone to typos. And I think you can't vectorize that loop: you have to explicitly calculate the inverse matrix for each k.

Matlab code for generating a particular class of matrices

I need to generate all square matrices of order n with given properties.
Matrices are symmetric.
Entries are 0 and 1.
Diagonal elements are zeros.
I am using Matlab2012b. Can you help me with the code?
I was trying to write it down. It needs a long sequences of for loops. Any simpler technique?
Try this:
N = 4; %// matrix size
M = (N^2-N)/2; %// number of values to fill in each matrix
P = 2^M; %// number of matrices
x = dec2bin(0:P-1)-'0'; %// each row contains the values of a matrix, "packed" in a vector
result = NaN(N,N,P); %// preallocate
for k = 1:P
result(:,:,k) = squareform(x(k,:)); %// unpack values
end
The matrices are result(:,:,1), result(:,:,2) etc.