To set value based on condition in a matrix

6 次查看(过去 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-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 CenterFile Exchange 中查找有关 Monte Carlo Analysis 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by