Matlab: What is the most efficient way to add zero rows (or column) to a sparse matrix? - matlab

Suppose I have an N x N sparse matrix. Take for example A = speye(N).
My general question is: what is the most efficient way to add zero rows (or column) to a sparse matrix?
Adding jj columns on the right side of the matrix and/or adding ii rows at the bottom of the matrix simply changes the size of the sparse matrix. So in code this would be
N=2;
A=speye(N);
[rows,cols,vals] = find(A);
% Add ii = 3 zero rows at the bottom
% and jj = 2 zero columns at the left of A
ii = 3; jj=2;
B = sparse(rows,cols,vals,N+ii,N+jj);
Adding columns on the left and at the top, also changes the indices.
N=2;
A=speye(N);
[rows,cols,vals] = find(A);
% Add ii = 3 zero rows at the top
% and jj = 2 zero columns at the right of A
ii = 3; jj=2;
B = sparse(rows+ii,cols+jj,vals,N+ii,N+jj);
Is there a more efficient way, for either of the two cases? For example, can I skip somehow finding the non-zero elements of A?

You can add a column as you would with a standard matrix
% Create a sparse matrix
A = speye(3);
% Add a column of zeros to the end
A(:, end+1) = 0;
Note that find will still only return the 2 non-zero values, but size(A)=[2,3], i.e we've successfully added a column.
Variants:
% Still adding a column on the right, by concatenating with another sparse matrix.
% However: this is less memory efficient with A on the right hand side
A = [A, sparse(3,1)];
% Adding column on the left
A = [sparse(3,1), A]; % comma is equivalent of 'horzcat'
% Adding a row on the top
A = [sparse(1,size(A,2)); A]; % semi-colon is equivalent of 'vertcat'

Related

Non-trivial reshape in chunks

I am trying to reshape a matrix, but not in the standard way. It is basically a "chunk" reshape. I have a column vector named matrix1 which is (T*N x 1) and a matrix named matrix2 which is TxN. I want the first N elements of the column vector matrix1 to be transposed into the first row of matrix2. Then the second chunk of N elements of vector matrix1 to be transposed into the second row of matrix2.
I know how to do it with a loop (see code below). Just wondering if there is a smarter way to do it.
T = 2;
N = 7;
matrix1 = rand(T*N,1);
matrix2 = NaN(T,N);
for t = 1:T
matrix2(t,:) = matrix1(t*N-N+1:t*N,1)';
end
Use reshape for reshaping... You literally describe a standard reshape in the text.
reshape(matrix1,N,T).'

MATLAB: Accessing Multidimensional Cell Matrix Index

I have cell matrix which the dimensions are changing according to user input. As a user, I want to use one dimension's certain index meanwhile whole the elements of the other dimensions exist. I think it is better to explain the situation with a certain example:
Assume that my cell matrix A whose sizes are 2x3x4x5x7. I want to use whole elements of 1.,3. and 4. dimension. At the same time only the 2. element of the 2. dimension and 3., 5. elements of 5. dimension. This can be achieved easily with :
A(:,2,:,:,[3 5]);
What about the case A is input of a function and dimensions are changing. How can I obtain this result with linear indexing or another way?
I know that there is no such a syntax but my situation can be described as follows:
whole_indexes = sub2ind(size(A),[:,2,:,:,[3,5]]);
A(whole_indexes)
This problem can be solved the with the code below:
size_A = size(A); % A is the matrix whose elements will be selected
whole_index = cellfun(#(x) 1:x,num2cell(size_A),'UniformOut',false); % create a cell array which includes all the possible numbers
all_sizes = cellfun(#length,whole_index); % each dimension size
%% select the desired indexes in your desired dimensions
whole_index{1} = [1 2]; % first dimension first 2 elements
whole_index{2} = [2]; % second dimension second element
all_numbers = combvec(whole_index{:}).'; % whole possibilities
all_numbers = mat2cell(all_numbers,max(size_nums),ones(1,min(size_nums))); % cell format of possibilities
comb_inds = sub2ind(all_sizes,all_numbers{:});
desired_out = A(comb_inds);
Another solution would be written like:
size_A = size(A); % A is the matrix whose elements will be selected
whole_index = cellfun(#(x) 1:x,num2cell(size_A),'UniformOut',false);
%% select the desired indexes in your desired dimensions
whole_index{1} = [1 2]; % first dimension first 2 elements
whole_index{2} = [2]; % second dimension second element
desired_out = A(whole_index{:});

select optimal column vector from a matrix subject to a localised goal vector constraint

How to automatically select the column vector of a matrix within which the scalar values in a subset of elements is closest to those in a predefined goal vector of the same sub set?
I solved the problem and tested method on 100,10 matrix, it works - should also work for larger matrices, while hopefully not becoming too computationally expensive
%% Selection of optimal source function
% Now need to select the best source function in the data matrix
% k = 1,2,...n within which scalar values of a random set of elements are
% closest to a pre-defined goal vector with the same random set
% Proposed Method:
% Project the columns of the data matrix onto the goal vector
% Calculate the projection error vector matrix; the null space of the
% local goal vector, is orthogonal to its row space
% The column holding the minimum error vector is the optimal column
% [1] find the null space of the goal vector, containing the projection
% errors
mpg = pinv(gloc);
xstar = mpg*A;
p = gloc*xstar;
nA = A-p;
% [2] the minimum error vector will correspond to the optimal source
% function
normnA = zeros(1,n);
for i = 1:n
normnA(i) = norm(nA(:,i));
end
minnA = min(normnA);
[row,k] = find(normnA == minnA);
disp('The optimal source function is: ')
disp(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.

Matlab: Access matrix elements using indices stored in other matrices

I am working in matlab. I have five matrices in ,out, out_temp,ind_i , ind_j, all of identical dimensions say n x m. I want to implement the following loop in one line.
out = zeros(n,m)
out_temp = zeros(n,m)
for i = 1:n
for j = 1:m
out(ind_i(i,j),ind_j(i,j)) = in(ind_i(i,j),ind_j(i,j));
out_temp(ind_i(i,j),ind_j(i,j)) = some_scalar_value;
end
end
It is assured that the values in ind_i lies in range 1:n and values in ind_j lies in range 1:m.
I believe a way to implement line 3 would give the way to implement line 4 , but I wrote it to be clear about what I want.
Code
%// Calculate the linear indices in one go using all indices from ind_i and ind_j
%// keeping in mind that the sizes of both out and out_temp won't go beyond
%// the maximum of ind_i for the number of rows and maximum of ind_j for number
%// of columns
ind1 = sub2ind([n m],ind_i(:),ind_j(:))
%// Initialize out and out_temp
out = zeros(n,m)
out_temp = zeros(n,m)
%// Finally index into out and out_temp and assign them values
%// using indiced values from in and the scalar value respectively.
out(ind1) = in(ind1);
out_temp(ind1) = some_scalar_value;