Reputation: 2299
I have a vector A
in Matlab of dimension (N-1)x1
A=[0:1:N-2]'
with N>=3
, e.g. with N=4 A=[0 1 2]
I want to construct a 3-dimensional matrix B
of dimension Mx(N-1)x(N-1)
without using loops such that e.g. with N=4
, M=5
B(:,:,1)=[0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0]
B(:,:,2)=[1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1]
...
B(:,:,end)=[N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2]
Upvotes: 0
Views: 44
Reputation: 16791
I'm going to keep using permute
until I get the hang of it...
B = ones(M,N-1,N-1).*permute(A,[3,2,1])
Upvotes: 2
Reputation: 112679
Is this what you want?
B = repmat(reshape(A,1,1,[]), M, N-1); %// or change N-1 to N, according to your example
Another possibility:
B = bsxfun(@times, reshape(A,1,1,[]), ones(M, N-1)); %// or change N-1 to N
Yet another:
B = reshape(A(ceil((1:numel(A)*M*(N-1))/M/(N-1))), M, N-1, []); %// or change N-1 to N
Upvotes: 2
Reputation: 104503
Here's one approach with kron
and reshape
:
A = 0:N-2;
B = reshape(kron(A, ones(M, N-1)), M, N-1, []);
We use kron
to produce M x (N-1)
2D matrices that are stacked for as many elements as there are in A
and each matrix is multiplied by the corresponding value in A
. The next step is to take each of the concatenated 2D matrices and place them as individual slices in the third dimension, done by reshape
.
M = 5, N = 4
>> B
B(:,:,1) =
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
B(:,:,2) =
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
B(:,:,3) =
2 2 2
2 2 2
2 2 2
2 2 2
2 2 2
Upvotes: 3