필터 지우기
필터 지우기

How can produce this matrix?

조회 수: 1 (최근 30일)
S AsZ
S AsZ 2023년 12월 6일
댓글: S AsZ 2023년 12월 6일
I want to produce a m×n matrix for example like this: x=[1 1 1 0 1 0 1 1; 0 0 0 1 0 1 0 0]  This matrix can give 0 or 1 for its elements. This 0 and 1 elements must be randomly distributed so that sum of each column is equal to one. I have a value like "k" that sum of the fisrt row can be equal or less than k. In defining the above matrix I also want to consider the following conditions: if the sum of the first row is less than k the all elements in the first row must be consider to 1 and all elements in the other rows must be zero. Otherwise, if the sum of the first row is equal to k the first row elements can be 0 or 1 but remind that the sum of each column must be 1.
  댓글 수: 5
S AsZ
S AsZ 2023년 12월 6일

Acctually I want to code the below constraints in an optimization problem with the solver-based optimization approach in matlab. But I do not know how to code this constraints. In the following equations "U" denotes a binary variable, "Cd_k" is a determined parameter with one row and k columns (1×k), "Qdc_kl" is a continuous variable with k rows and l columns in which in each column just one element can be positive and the others are zero. Finally, "Y_k" is a binary variable wich is equal or less than to U. Actually, I am trying to code this constraints but I do not know how can define this constraints with solver-based optimization of matlab 😕 Can you help me?

S AsZ
S AsZ 2023년 12월 6일
So I tried to define "Qdc_kl" as a matrix in which sum of each column is equal to 1 to ensure that each column has only one positive value and the other values are equal to zero and also I wanted to ensure that the sum of each rows are less than or equal to "Cd_k"

댓글을 달려면 로그인하십시오.

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 12월 6일
편집: Dyuman Joshi 2023년 12월 6일
M = 3; N = 7;
k=2;
arr = accumarray([randi(M,1,N); (1:N)].', 1, [M N])
arr = 3×7
1 1 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 1 0 0
if sum(arr(1,:))<k
arr = [ones(1,N);zeros(M-1,N)];
end
arr
arr = 3×7
1 1 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 1 0 0

추가 답변 (1개)

Walter Roberson
Walter Roberson 2023년 12월 6일
편집: Walter Roberson 2023년 12월 6일
For the sum of each column to be 1, and the elements are each 0 or 1, then it follows that for every column, there must be exactly 1 row that is set to 1. You can use randi() to select the rows.
M = 5; N = 4;
matrix = zeros(M, N);
matrix(sub2ind([M,N], randi(M, N, 1), (1:N).' )) = 1;
matrix
matrix = 5×4
0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by