-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvec2mat.m
50 lines (41 loc) · 1.17 KB
/
vec2mat.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function mat = vec2mat(vec, full)
% mat = vec2mat(vec, full)
%returns the correlation matrix from a vector.
% If vec is [p x n*(n-1)/2], returns [p x n x n]
% if full == 1, returns the symmetric matrix
if nargin<2
full = 1;
end
if isvector(vec)
N = length(vec);
n = 1/2 + sqrt(1+8*N)/2;
mat = nan*ones(n);
% mat = zeros(n);
temp = ones(n);
%% find the indices of the lower triangle of the matrix
IND = find((temp-triu(temp))>0);
mat(IND) = vec;
if full
tempmat = flipud(rot90(mat));
tempmat(IND) = vec;
mat = flipud(rot90(tempmat));
end
elseif ndims(vec) == 2
[p,N] = size(vec);
n = 1/2 + sqrt(1+8*N)/2;
mat = zeros([p,n,n]);
temp = ones(n);
%% find the indices of the lower triangle of the matrix
IND = find((temp-triu(temp))>0);
for ii = 1:p
tempmat = zeros(n);
tempmat(IND) = vec(ii,:);
if full
tempmat2 = flipud(rot90(tempmat));
tempmat2(IND) = vec(ii,:);
mat(ii,:,:) = flipud(rot90(tempmat2));
else
mat(ii,:,:) = tempmat;
end
end
end