Hi, the below code generates the dimensions m, n, and r randomly, ensuring that r is always less than or equal to the minimum of m and n. It then constructs a matrix X as the product of two random matrices of sizes (m×r) and (r×n). Based on the dimensions of X, the function “generate_L “ creates a matrix L of size either (m×r) or (r×n), using randomly permuted identity matrices. This ensures L has only one nonzero entry per column while adapting to the input matrix X.
Finally, the code outputs the randomly chosen values of m, n, and r, along with the size of L, making the entire process fully automated and flexible.
function L = generate_L(X, r)
[m, n] = size(X);
% Determine the size of L based on X
if m >= n
L = generate_permutation_matrix(m, r); % Size [m x r]
else
L = generate_permutation_matrix(r, n); % Size [r x n]
end
end
function L = generate_permutation_matrix(rows, cols)
L = [];
I = eye(rows);
for i = 1:cols
permuted_I = I(randperm(rows), :); % Random permutation of identity
L = [L, permuted_I]; % Construct the final matrix
end
end
m = randi([5, 15]);
n = randi([5, 15]);
r = randi([min(m, n)-2, min(m, n)]); % Random r ensuring 1 <= r <= min(m, n)
X = rand(m, r) * rand(r, n);
L = generate_L(X, r);
disp(['m = ', num2str(m), ', n = ', num2str(n), ', r = ', num2str(r)]);
disp('Size of L:');
disp(L)
disp(size(L)); % Will output either [m x r] or [r x n]