How to represent a vector as a matrix? - matlab

I have a vector of length 3. i want to represent it as a matrix of dimension 4*2. ie) if the length of vector is n then matrix should be of dimension (n+1)*2. The matrix should have elements arranged as follows:
Vector= [2 3 4]
Matrix = [0 2;2 3;3 4;4 0]

You can solve your problem easily with simple operations:
vector = [2 3 4];
matrix = [0 vector; vector 0]';
' is used to transpose the matrix.
Additionally there are two useful functions in Matlab to manipulate matrices and vectors:
reshape()
repmat()

The command reshape from Matlab is the basis of my answer to your question:
B = reshape(A,m,n) returns the m-by-n matrix B whose elements are taken column-wise from A. An error results if A does not have m*n elements (from the official Matlab help).
You basically add zeros at the beginning and at the end and then have every number in the vector occur twice (if you "unfold"/reshape the matrix). So lets construct the desired matrix by reversing this description:
%set input vector
v = [2 3 4];
%"double" the numbers, v_ is my temporary storage variable
v_ = [v; v];
%align all numbers along one dimension
v_ = reshape(v_, 2*length(v), 1)
%add zeros at beginning and end
v_ = [0 v_ 0];
%procude final matrix
m = reshape(v_, length(v)+1, 2);
in short
%set input vector
v = [2 3 4];
%"double" the numbers, v_ is my temporary storage variable
%all values are aligned as row vector
%zeros are added at beginning and end
v_ = [0, v, v, 0];
%produce final matrix
m = reshape(v_, length(v)+1, 2);
I haven't checked it, since I don't have a Matlab at hand right now, but you should get the idea.
Edit
The answer by 13aumi manages this task even without the reshape command. However, you need to pay close attention to the shape of v (row- vs- column-vector).

Related

Replacing elements in a base matrix by squared permutation submatrices

I have a sparse parity check matrix (consisting of ones and zeros) and I would need to replace each nonzero element (ones) from it by PM: a squared permutation matrix of dimension N (being N generally a large integer). In the case of the zero elements, these would be replaced by squared null matrices of the same dimension.
Let me share with you which the current state of my code is:
This is the base matrix in which I would like to replace its ones by permutation matrices:
B = zeros((L + ms) * dc, L * dv);
for i = 1 : 1 : L
for j = 1 : 1 : dv
B(dc*(i-1)+1 : dc*(ms+i), j+dv*(i-1)) = ones(dc*(ms+1), 1);
end
end
I have been told a way for doing so by using 'cell' objects, this is, initializing H as an array of empty cells that would contain the corresponding submatrices:
H=repmat({{}},size(B));
Mc = 500 % Dimension of the permutation matrix
MP=randi([1,5],Mc,Mc); % Definition of one permutation matrix
% It would be desirable that the permutation matrix is different for each replacement
[H{B==0}]=deal(zeros(Mp));
[H{B==1}]=deal(MP);
But there's one problem coming up -that I would need this matrix to be used as a parameter of a following function and it would be very much desirable that it were a simple matrix of ones and zeros (as I am not very familiar with 'cell' structures... however, as you can see, Mc is such a big integer that I don't know if that would be possible to be handled.
Do you have any other way of doing so to have a raw matrix of dimensions (L*ms)dcMc, LdvMc as output?
These are some parameters that could be used to have a try:
ms = 2;
Mc = 600; % any number (specially big ones) could serve for this purpose
dc = 3;
dv = 4;
L = 15;
Many thanks in advance for your attention, and may you have a nice day.
This is how it can be done with cells:
B = Randi([0,1], m, n); % m*n array of 1s and 0s
H = cell(size(B)); % Define cell array
Mc = 500; % Size of replacement matrices
MP = randi([1,5], Mc, Mc); % Permutation matrix
H(B==0) = {zeros(Mc, Mc)}; % Set elements of H where B==0 to matrix of zeros
H(B==1) = {MP}; % Set elements of H where B==1 to permutation matrix
% Convert to matrix
Hmat = cell2mat(H); % Hmat = Mc*m row by Mc*n column matrix
Each cell element holds a matrix of size Mc*Mc, at the end this can be converted to one large matrix. Take care which sorts of brackets you use with cells, the parentheses () are for logical indexing, whilst the curly braces {} are for assigning the sub-matrixes as cell elements.
Example:
B = [1 0; 1 1];
MP = [1 2; 3 4];
H(B==0) = {zeros(2, 2)};
H(B==1) = {MP};
Hmat = cell2mat(H);
% >> Hmat = [1 2 0 0
% 3 4 0 0
% 1 2 1 2
% 3 4 3 4];
If you want the replacement matrix MP to change, you will have to do this in a loop, changing MP on each iteration and using it to replace one element of H.

kronecker product for an array of matrices [duplicate]

I have two tensor: x is 2-by-2-by-3, y is also 2-by-2-by-3. Define each frontal slice of tensor is x1 x2 x3,y1,y2,y3. xi or yi are 2-by-2 matrix. How can I do kronecker product between x and y in matlab? What I want to get is kron(x1,y1),kron(x2,y2),kron(x3,y3) in matlab simultaneously without any looping.
This works for arbitrary sizes of x and y:
Build a 5D array z. The first two dimensions contain the products of combinations of rows of x and y; the next two contain the products of combinations of columns of x and y; and the fifth is the original third dimension.
That arrray is reshaped, collapsing dimensions first ant second on one hand, and third and fourth on the other hand, to produce the final result:
Code:
z = bsxfun(#times, permute(x, [4 1 5 2 3]), permute(y, [1 4 2 5 3])); %// step 1
z = reshape(z, size(x,1)^2, size(x,2)^2, size(x,3)); %//step 2
This could be one approach -
%// Pre-processing part
[m,n,r] = size(x) %// Get size
N = m*n %// number of elements in one 3D slice
%// ------------- PART 1: Get indices for each 3D slice
%// Get the first mxm block of kron-corresponding indices and then add to
%// each such block for the indices corresponding to the kron multiplications
%// of each iteration
a1 = bsxfun(#plus,reshape([0:N-1]*N+1,m,m),permute([0:N-1],[1 3 2]))
%// Now, a1 is a 3D array, we need to make 2D array out of it.
%// So, concatenate along rows to make it a "slimish" 2D array
a2 = reshape(permute(a1,[1 3 2]),size(a1,1)*size(a1,3),[])
%// Cut after every N rows to make it a square 2D array.
%// These are the indices for each frontal tensor of kron muliplications
slice_idx = reshape(permute(reshape(a2,N,size(a2,1)/N,[]),[1 3 2]),N,N)
%// ------------- PART 2: Get kron equivalent output
%// Perform x:(Nx1) x y:(1xN) multiplications
vals = bsxfun(#times,reshape(x,m*n,1,r),reshape(y,1,m*n,r)) %//multiplications
%// Get indices for all 3D slices and then index into those multiplications
%// with these for the final kron equivalent output
all_idx=bsxfun(#plus,slice_idx,permute([0:r-1]*m*m*n*n,[1 3 2])) %//all indices
out = vals(all_idx) %// final output of kron equivalent multiplications

For loop through all elements of vector of ones

In Matlab, say that I have a 3x1 vector of ones. Then I want to do a for loop, changing one element to a zero. So that I get (0,1,1), (1,0,1) and (1,1,0) from my loop. How can I go about this?
I have tried
for i = s
i = 0;
print(s);
end
where s is my vector, but it doesn't work. Note that I'm a beginner at programming.
Thank you!
Instead of showing what's wrong with your code, I'll show you a more Matlab-like way to do it:
n = 3; %// problem size
matrix = ones(n)-eye(n); %// n x n matrix with all ones except zeros at the diagonal
for k = 1:n %// pick each row
disp(mat2str(matrix(k,:))) %// create a string from n-th row and display it
end
Result:
[0 1 1]
[1 0 1]
[1 1 0]

Kronecker product between two tensors

I have two tensor: x is 2-by-2-by-3, y is also 2-by-2-by-3. Define each frontal slice of tensor is x1 x2 x3,y1,y2,y3. xi or yi are 2-by-2 matrix. How can I do kronecker product between x and y in matlab? What I want to get is kron(x1,y1),kron(x2,y2),kron(x3,y3) in matlab simultaneously without any looping.
This works for arbitrary sizes of x and y:
Build a 5D array z. The first two dimensions contain the products of combinations of rows of x and y; the next two contain the products of combinations of columns of x and y; and the fifth is the original third dimension.
That arrray is reshaped, collapsing dimensions first ant second on one hand, and third and fourth on the other hand, to produce the final result:
Code:
z = bsxfun(#times, permute(x, [4 1 5 2 3]), permute(y, [1 4 2 5 3])); %// step 1
z = reshape(z, size(x,1)^2, size(x,2)^2, size(x,3)); %//step 2
This could be one approach -
%// Pre-processing part
[m,n,r] = size(x) %// Get size
N = m*n %// number of elements in one 3D slice
%// ------------- PART 1: Get indices for each 3D slice
%// Get the first mxm block of kron-corresponding indices and then add to
%// each such block for the indices corresponding to the kron multiplications
%// of each iteration
a1 = bsxfun(#plus,reshape([0:N-1]*N+1,m,m),permute([0:N-1],[1 3 2]))
%// Now, a1 is a 3D array, we need to make 2D array out of it.
%// So, concatenate along rows to make it a "slimish" 2D array
a2 = reshape(permute(a1,[1 3 2]),size(a1,1)*size(a1,3),[])
%// Cut after every N rows to make it a square 2D array.
%// These are the indices for each frontal tensor of kron muliplications
slice_idx = reshape(permute(reshape(a2,N,size(a2,1)/N,[]),[1 3 2]),N,N)
%// ------------- PART 2: Get kron equivalent output
%// Perform x:(Nx1) x y:(1xN) multiplications
vals = bsxfun(#times,reshape(x,m*n,1,r),reshape(y,1,m*n,r)) %//multiplications
%// Get indices for all 3D slices and then index into those multiplications
%// with these for the final kron equivalent output
all_idx=bsxfun(#plus,slice_idx,permute([0:r-1]*m*m*n*n,[1 3 2])) %//all indices
out = vals(all_idx) %// final output of kron equivalent multiplications

Getting the N-dimensional product of vectors

I am trying to write code to get the 'N-dimensional product' of vectors. So for example, if I have 2 vectors of length L, x & y, then the '2-dimensional product' is simply the regular vector product, R=x*y', so that each entry of R, R(i,j) is the product of the i'th element of x and the j'th element of y, aka R(i,j)=x(i)*y(j).
The problem is how to elegantly generalize this in matlab for arbitrary dimensions. This is I had 3 vectors, x,y,z, I want the 3 dimensional array, R, such that R(i,j,k)=x(i)*y(j)*z(k).
Same thing for 4 vectors, x1,x2,x3,x4: R(i1,i2,i3,i4)=x1(i1)*x2(i2)*x3(i3)*x4(i4), etc...
Also, I do NOT know the number of dimensions beforehand. The code must be able to handle an arbitrary number of input vectors, and the number of input vectors corresponds to the dimensionality of the final answer.
Is there any easy matlab trick to do this and avoid going through each element of R specifically?
Thanks!
I think by "regular vector product" you mean outer product.
In any case, you can use the ndgrid function. I like this more than using bsxfun as it's a little more straightforward.
% make some vectors
w = 1:10;
x = w+1;
y = x+1;
z = y+1;
vecs = {w,x,y,z};
nvecs = length(vecs);
[grids{1:nvecs}] = ndgrid(vecs{:});
R = grids{1};
for i=2:nvecs
R = R .* grids{i};
end;
% Check results
for i=1:10
for j=1:10
for k=1:10
for l=1:10
V(i,j,k,l) = R(i,j,k,l) == w(i)*x(j)*y(k)*z(l);
end;
end;
end;
end;
all(V(:))
ans = 1
The built-in function bsxfun is a fast utility that should be able to help. It is designed to perform 2 input functions on a per-element basis for two inputs with mismatching dimensions. Singletons dimensions are expanded, and non-singleton dimensions need to match. (It sounds confusing, but once grok'd it useful in many ways.)
As I understand your problem, you can adjust the dimension shape of each vector to define the dimension that it should be defined across. Then use nested bsxfun calls to perform the multiplication.
Example code follows:
%Some inputs, N-by-1 vectors
x = [1; 3; 9];
y = [1; 2; 4];
z = [1; 5];
%The computation you describe, using nested BSXFUN calls
bsxfun(#times, bsxfun(#times, ... %Nested BSX fun calls, 1 per dimension
x, ... % First argument, in dimension 1
permute(y,2:-1:1) ) , ... % Second argument, permuited to dimension 2
permute(z,3:-1:1) ) % Third argument, permuted to dimension 3
%Result
% ans(:,:,1) =
% 1 2 4
% 3 6 12
% 9 18 36
% ans(:,:,2) =
% 5 10 20
% 15 30 60
% 45 90 180
To handle an arbitrary number of dimensions, this can be expanded using a recursive or loop construct. The loop would look something like this:
allInputs = {[1; 3; 9], [1; 2; 4], [1; 5]};
accumulatedResult = allInputs {1};
for ix = 2:length(allInputs)
accumulatedResult = bsxfun(#times, ...
accumulatedResult, ...
permute(allInputs{ix},ix:-1:1));
end