To set value based on condition in a matrix

21 ビュー (過去 30 日間)
yue ishida
yue ishida 2012 年 8 月 30 日
Hi. I have a problem to set up value in a matrix. I have a A=m*n matrix. For example, m=13, and n=7. So, my coding will be like this.
A=zeros(m,n);
A=
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
So, I need to put value x=1 into matrix A based on algorithm as below:
1. x need to appear in every row of matrix A. The outcome will be like as below:
A=
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
3. The value of x of first row may start in first column, second column, or any column (random selection), but the value x of the next row is put after one column of previous row. For example, if value x is start in first row in 5 column, the matrix will become like this:
A=
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0

回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2012 年 8 月 30 日
編集済み: Andrei Bobrov 2012 年 9 月 1 日
m=13; % [m,n] - size of our matrix
n=7;
i1 = 5;
x = 1;
B = repmat(x*eye(n),2*ceil(m/n),1);
Bout = B(i1:i1+m,:);
  2 件のコメント
syamil syam
syamil syam 2012 年 9 月 1 日
the answer is very helpful. but how if i want to put one more value like x=1, y= 2 without change the matric size?
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 1 日
syamil, this is not your question, because it's posted by Yue in another question. http://www.mathworks.com/matlabcentral/answers/47165-how-to-set-more-than-1-value-to-this-code

サインインしてコメントする。


Azzi Abdelmalek
Azzi Abdelmalek 2012 年 8 月 30 日
編集済み: Azzi Abdelmalek 2012 年 9 月 1 日
x=1;
n=13,m=7,n1=5 ; A=zeros(n,m);% n1 is your random number
A(sum([ 1:n; mod(n1-1:n+n1-2,m)*n]))=x
%to add another x=2 (for example) with n1=4; repeat
x=2;n1=4
A(sum([ 1:n; mod(n1-1:n+n1-2,m)*n]))=x
  1 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 1 日
編集済み: Azzi Abdelmalek 2012 年 9 月 1 日
% you just change the value x and n1;
x=2;n1=4; %n1 your another random number
A(sum([ 1:n; mod(n1-1:n+n1-2,m)*n]))=y

サインインしてコメントする。


Matt Fig
Matt Fig 2012 年 8 月 30 日
編集済み: Matt Fig 2012 年 8 月 30 日
Here is an example.
% First make the matrix and get the needed numbers...
A = zeros(ceil(rand(1,2)*10)+1); % The matrix, a random size.
[M,N] = size(A);
c = ceil(rand*N); % Starting column in row 1.
% And now for the method....
idx = mod(c:c+M-1,N);
idx(~idx) = N;
A((1:M) + (idx-1)*M) = 1

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by