How to change 0 to 1 and update a matrix

10 ビュー (過去 30 日間)
Antonio Grivas
Antonio Grivas 2019 年 6 月 21 日
回答済み: Antonio Grivas 2019 年 6 月 22 日
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 :)
  5 件のコメント
Stephen23
Stephen23 2019 年 6 月 21 日
編集済み: Stephen23 2019 年 6 月 21 日
@Antonio Grivas: Whenever I run your code it always returns this:
G =
0 4 4 4
0 4 4 4
0 4 4 4
0 4 4 4
It is unclear how this output relates to your examples.
Please explain the logic of what you are trying to achieve.
Antonio Grivas
Antonio Grivas 2019 年 6 月 21 日
It is completely wrong. I don't know how to make it change the final result whick would be
1
0
0
0
1 0
0 1
0 0
0 0
1 0 0
0 1 0
0 0 1
0 0 0
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
I send the (without the wrong loop) answer where the program runs correctly only the first time
I suppose that i need a
for i = 1:size(whatever)
whatever(: , i) = 0
whatever(: , a) = 1
end
that sould be put somewhere to keep the previous results and not change it back to
0
0
0
0
and change the position of the 1 after adding a column
If you run it just check only the 1st time before it changes it back to
0
0
1
0
becomes
0 1
0 0
1 0
0 0
Then for some reason that i cannot see does not continue but gives
0 4
0 4
0 4
0 4
I am trying to be precise if i can to help you
Thank you

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 6 月 21 日
編集済み: Andrei Bobrov 2019 年 6 月 22 日
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);
  4 件のコメント
Antonio Grivas
Antonio Grivas 2019 年 6 月 21 日
Problem with matrix dimensions at k = y1.*eye(n);
Andrei Bobrov
Andrei Bobrov 2019 年 6 月 22 日
You use old MATLAB.
Replace this expression with the following:
k = bsxfun(@times,y1,eye(n));

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

その他の回答 (1 件)

Antonio Grivas
Antonio Grivas 2019 年 6 月 22 日
Thank you very much
Matlab version 2016a (that was the problem)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by