Asked by Antonio Grivas
on 21 Jun 2019

clc

clear all

close all

b1 = [10; 20 ; 30 ; 40];

A = [0 20 0 10 ; 20 0 30 0 ; 0 30 0 10 ; 20 0 10 0];

s = size(b1);

x = randi([0 1],s)

G = [];

[ n m ] = size(x);

for i = 1 : n

for j = 1 : m

G(:,i) = x(:,j)

a = find(G(: , i) == 0 , 1 , 'first')

[x y] = size(G(:,i))

for k = 1:y

G(: , k) = 0;

G(a , k) = 1

end

end

i = i + 1;

j = j + 1;

end

This prob wil work only the first time. I want the matrix to take a column, find where the first 0 is and change it to 1. Then proceed to the next line and do the same but keep the first column and not change it to 0s. Final solution must look like

x =

0

1

0

0

(x changes randomly with 0 and 1 )

G =

1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

I would appreciate any answer :)

Answer by Andrei Bobrov
on 21 Jun 2019

Edited by Andrei Bobrov
on 22 Jun 2019

Accepted Answer

n = numel(x1);

y1 = ~x1;

% if MATLAB >= R2016b

k = y1.*eye(n);

% if MATLAB <= R2016a

k = bsxfun(@times,y1,eye(n));

out = [x1, zeros(n,n-1)];

p = find(y1);

out(:,2:numel(p)+1) = k(:,p);

Antonio Grivas
on 21 Jun 2019

I will run this program as soon as i finish from work and go home.

Thanks in advance

Antonio Grivas
on 21 Jun 2019

Problem with matrix dimensions at k = y1.*eye(n);

Andrei Bobrov
on 22 Jun 2019

You use old MATLAB.

Replace this expression with the following:

k = bsxfun(@times,y1,eye(n));

Sign in to comment.

Answer by Antonio Grivas
on 22 Jun 2019

Thank you very much

Matlab version 2016a (that was the problem)

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 5 Comments

## Chinmay Anand (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/468230-how-to-change-0-to-1-and-update-a-matrix#comment_716889

## Antonio Grivas (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/468230-how-to-change-0-to-1-and-update-a-matrix#comment_716896

## Antonio Grivas (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/468230-how-to-change-0-to-1-and-update-a-matrix#comment_716899

## Stephen Cobeldick (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/468230-how-to-change-0-to-1-and-update-a-matrix#comment_716902

## Antonio Grivas (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/468230-how-to-change-0-to-1-and-update-a-matrix#comment_716991

Sign in to comment.