How to get numbers from rows in a matrix, to separate vectors?

2 ビュー (過去 30 日間)
Emil Christensen
Emil Christensen 2020 年 1 月 23 日
編集済み: Stephen23 2020 年 1 月 27 日
I have a matrix of grades, I want to put the number of times grades repeat in each row into separate vectors so I can plot it in a scatter plot.
I have the matrix
grades=
7 7 4
12 10 10
-3 7 2
10 12 12
4 2 10
10 7 4
7 7 9
12 12 12
2 7 12
0 -3 2
4 10 2
2 12 10
10 3 4
12 12 12
I want to know how many times each number repeats in each row, and put them in a vector for each row

回答 (1 件)

Samatha Aleti
Samatha Aleti 2020 年 1 月 27 日
According to my understanding you are trying to get the count of numbers in each row and save it in another vector. You can use “find” function to do this.
Let grades be the matrix, out be the output vector which holds the count of element “1” in each row.Here is a sample code to do this:
grades = [1 2 3; 3 2 1; 1 2 1; 1 2 3; 1 3 1;1 1 3]; % Let
numRows = size(grades,1); % Number of rows
out= zeros(1,numRows); % Initialize a vector to store the count
for i = 1:numRows
out(i) = length(find(grades(i,:) == 1));
end
Refer the following document link for detailed explanation on using "find":
  1 件のコメント
Stephen23
Stephen23 2020 年 1 月 27 日
編集済み: Stephen23 2020 年 1 月 27 日
More efficient than using length(find(...)):
nnz(grades(i,:) == 1)

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by