picking numbers from matrix

2 visualizzazioni (ultimi 30 giorni)
Berfin Çetinkaya
Berfin Çetinkaya il 17 Mar 2022
I have a matrix and it contains some numbers. I want to select a random number from each column in this matrix and print it in another single row matrix (one of the numbers except 0). but I don't want to print the 0 values to the new matrix.
example :
my matrix :
0 4 8
5 0 0
0 4 6
2 8 0
0 0 7
new matrix :
2 4 6
how can I do that?
Thank you,
Berfin.

Risposta accettata

Stephen23
Stephen23 il 17 Mar 2022
M = [0,4,8;5,0,0;0,4,6;2,8,0;0,0,7]
M = 5×3
0 4 8 5 0 0 0 4 6 2 8 0 0 0 7
fh1 = @(v)v(randperm(numel(v),1));
fh2 = @(k)fh1(nonzeros(M(:,k)));
V = arrayfun(fh2,1:size(M,2))
V = 1×3
2 4 7
  1 Commento
Berfin Çetinkaya
Berfin Çetinkaya il 17 Mar 2022
I have one more question. Can you help me?
, I have created such a code. My goal is to get the first, third, fifth, seventh etc from matrix A. was to assign values to the columns. ( ie odd numbers ) But I need the newM matrix to assign these values. I want to choose a random number from the second column (except 0) in the newM matrix and assign it to the first column in matrix A. I want to apply the same operation on multiple column.
example :
newM matrix:
0 5 8 3
1 7 0 4
5 4 2 1
4 0 6 7
A matrix:
1 8
5 6
4 4
4 5
(I chose random number from newM 4 times)
(a column in between leaves a space)
I know it's a bit confusing, but I need help because I can't do it. I will write the first phase value below. please help me. thanks
my code =
newM=birincifaz.*(1:size(birincifaz,1))';
birincifaz=
1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
3 1 0 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1 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by