Creating diagonal matrix from array of matrices in MATLAB - arrays

I am interested how to create a diagonal matrix from an array of matrices.
I created an array of matrices in MATLAB:
X<62x62x1000> it consists of 1000 matrices with dimensions 62x62
I want to create a matrix of dimensions 62000x62000 with 1000 sub matrices from array X along main diagonal.
Do you have any clue how to do this, except M=blkdiag(X(:,:,1), X(:,:,2), X(:,:,3)...) because that would be to much writing.

A possible solution
M = kron(speye(1000),ones(62));
M(logical(M)) = X(:);
With kron a 62000*62000 sparse matrix M is created that contains 1000 blocks of ones on its diagonal, then replace ones with elements of X.

You can flatten out your input matrix into a column vector using (:) indexing and then pass it to diag to place these elements along the diagonal of a new matrix.
result = diag(X(:))
This will order the elements along the diagonal in column-major order (the default for MATLAB). If you want a different ordering, you can use permute to re-order the dimensions prior to flattening.
It's important to note that your resulting matrix is going to be quite large. You could use spdiags instead to create a sparse diagonal matrix
spdiags(X(:), 0, numel(X), numel(X))

A very controversial eval call can solve this very lazily, although I suspect there is a much better way to do this:
evalstring = ['M=blkdiag('];
for i = 1:999
evalstring = [evalstring, 'X(:,:,', num2str(i),'),'];
end
evalstring = [evalstring, 'X(:,:,1000));'];
eval(evalstring);

Related

Sub2ind with three dimension - access all of dimension

Say A is a 3x4x5 array. I am given a vector a, say of dimension 2 and b of dimension 2. If I do A(a,b,:) it will give 5 matrices of dimensions 2x2. I instead want the piecewise vectors (without writing a for loop).
So, I want the two vectors of A which are given by (a's first element and b's first element) and (a's second element and b's second element)
How do I do this without a for loop? If A were two dimensions I could do this using sub2ind. I don't know how to access the entire vectors.
You can use sub2ind to find the linear index to the first element of each output vector: ind = sub2ind(size(A),a,b). To get the whole vectors, you can't do A(ind,:), because the : has to be the 3rd dimension. However, what you can do is reshape A to be 2D, collapsing the first two dimensions into one. We have a linear index to the vectors we want, that will correctly index the first dimension of this reshaped A:
% input:
A = rand(3,4,5);
a = [2,3];
b = [1,2];
% expected:
B = [squeeze(A(a(1),b(1),:)).';squeeze(A(a(2),b(2),:)).']
% solution:
ind = sub2ind(size(A),a,b);
C = reshape(A,[],size(A,3));
C = C(ind,:)
assert(isequal(B,C))
You can change a and b to be 3d arrays just like A and then the sub2ind should be able to index the whole matrix. Like this:
Edit: Someone pointed out a bug. I have changed it so that a correction gets added. The problem was that ind1, which should have had the index number for each desired element of A was only indexing the first "plane" of A. The fix is that for each additional "plane" in the z direction, the total number of elements in A in the previous "planes" must be added to the index.
A=rand(3,4,5);
a=[2,3];
b=[1,2];
a=repmat(a,1,1,size(A,3));
b=repmat(b,1,1,size(A,3));
ind1=sub2ind(size(A),a,b);
correction=(size(A,1)*size(A,2))*(0:size(A,3)-1);
correction=permute(correction,[3 1 2]);
ind1=ind1+repmat(correction,1,2,1);
out=A(ind1)

Squeeze Some of Singleton Dimensions in Matlab

How can I squeeze only a subset of singleton dimensions of a matrix in Matlab? The squeeze function removes them all.
I keep the index to those dimensions in a vector called "dims".
Code
%// Input matrix is assumed as A
sz = size(A)
t2 = sz~=1
t2(dims)=1
out = reshape(A,sz(t2)) %// out is the desired output
If you are crazy about dense codes, you can try this -
sz = size(A)
out = reshape(A,sz(sort([dims find(sz~=1)])))
In Matlab, there is no tailing singleton dimension. A n*m*1 matrix is automatically a n*m matrix. Knowing this, your problem could be solved permuting the dimensions you don't want to the end:
X=ones(2,1,2,1,2,1,2,1,2,1)
%dimensions you want to keep in any case
dims=[2:4];
%Notice, S is [2,1,2,1,2,1,2,1,2], last dimension already "gone"
S=size(X)
%keep if size>1
dimensions_to_keep=S>1
%and keep if in "dims" list
dimensions_to_keep(dims)=1
%now permute dimensions you don't want to the end
Y=permute(X,[find(dimensions_to_keep),find(~dimensions_to_keep)])

Multiplying array columns by vector

I'm new to R and I am certain that this is simple yet I can't seem to find an answer. I have an array [36,21,12012], and I need to multiply all of the columns by a vector of the same length to create a new array of the same dimensions.
If v is your vector and a is your array, in your case it would be as simple as v * a, because arrays are built column-wise. But in general, you would use sweep. For example to multiply along the rows, sweep(a, MARGIN=2, STATS=v, FUN='*').

How to store vector coordinates in Matlab

what's the best way to store vector coordinates in Matlab?
For example, h is the height of the image, w is the width, how can I do this (pseudocode):
vectors = [];
for i=1:h
for j=1:w
vectors += p(i,j);
end
end
To get the kth p object from vectors, I can use vector(k).
Thank you very much.
Array growth in MATLAB works by indexing past the last element:
vectors(end+1) = p(i,j);
Conventional wisdom is that it is better to pre-allocate your array and use indexing, but automatic array growth has become much more efficient, especially for cells and arrays of non-builtin objects.
However, you can just get what you want out of p directly via [ii,jj] = ind2sub(size(p),k); p(jj,ii). Note the order jj,ii to match your loop semantics, which would create a vector that indexes the elements of p in a row-major order vs. MATLAB's native column-major ordering. That is, p(2) refers to row 2, column 1 of p, but your vectors(2) would contain to row 1, column 2 of p using your loop order.
You can use p(k) directly. It is equivalent to p(i,j) where [i,j] = ind2sub([h w], k).
Documentation for ind2sub
Unless I didn't understand your question…

matlab vectorization varying array

Can anyone tell me what the basic idea behind varying rows or columns in a matrix with respect to the row/column number is in matlab? I've been trying to replace all the columns in a given matrix by
i=1:101;
V=ones(121,101);
V_t=1000*10.^((i-1)/20);
e=V_arr(1:121)';
V_arr=V; V_arr(:,i)=V_t*e;
I know that the error lies in trying to replace a number of columns with respect to all rows, and I've seen an alternative, simpler method using repmat, but I'd like to know if there's a method similar to the one above.
Thanks.
One thing you can do is to use matrix multiplication, i.e. a n-by-1 array multiplied by an 1-by-m array creates a n-by-m array.
For example
ii = 1:101; %# 1-by-101
V_t = 1000*10.^((i-1)/20);
ee = ones(121,1); %# 121-by-1
V_arr = ee * V_t;

Resources