To set value based on condition in a matrix

5 views (last 30 days)
yue ishida
yue ishida on 30 Aug 2012
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

Answers (3)

Andrei Bobrov
Andrei Bobrov on 30 Aug 2012
Edited: Andrei Bobrov on 1 Sep 2012
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 Comments
syamil syam
syamil syam on 1 Sep 2012
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?

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 30 Aug 2012
Edited: Azzi Abdelmalek on 1 Sep 2012
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 Comment
Azzi Abdelmalek
Azzi Abdelmalek on 1 Sep 2012
Edited: Azzi Abdelmalek on 1 Sep 2012
% 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

Sign in to comment.


Matt Fig
Matt Fig on 30 Aug 2012
Edited: Matt Fig on 30 Aug 2012
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

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!