make an r by m permutation matrix

I have the following code :
A = eye(r);
L = [];
for i = 1:10
A = A(randperm(r),:);
L = [L A]; % 10 x 100 matrix with only one nonzero entry per column
end
The variable L is a 10x 100 size matrix. however i want to make a more intelligent code such that,
the dimensions will depend on the dimension of an input data matrix. for example when i input X, i.e.
% r is my rank. m and n are the dimensions.
X = rand(m,r)* rand(r,n);
% I want L to have dimension of [m by r] or [r by n] .
% i.e. it should pick on of the sides of X and the other side r

답변 (1개)

Parag
Parag 2025년 3월 5일

0 개 추천

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]

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2021년 4월 6일

답변:

2025년 3월 5일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by