Hello, I am new to Matlab and want help to count number of rows in a matrix that belong to data subset.

2 vues (au cours des 30 derniers jours)
For example consider a random Matrix of 12*2. I want to count the number of rows from 4th row to the 7th row using a code(that will be 4 rows). The 8th row will contain NaN or any other identifier for example -999 to show that the first data set ends at row 7 and the next dataset begins at row 9. It is also possible to include a distinguishing identifier on the row before the data subset begins. Therefore for example with respect to the following matrix, I would like to write a code that will count the number of rows starting from the first identifier i.e. NaN upto the next identifier i.e. -999 (the identifiers need not be as NaN or -999 and can be anything that helps me to distinguish between the dataset).
Thank you for the help
% Example matrix
4 7
6 8
NaN NaN
0.2 0.5
0.3 0.9
0.1 0.7
0.6 0.4
-999 -999
1.6 1.9
2.8 6.4
5.1 8.3
2.3 4.7

Réponse acceptée

Jos (10584)
Jos (10584) le 13 Août 2018
Let A be your matrix, as above. I suggest you study the outcome of each step below:
tf1 = isnan(A)
tf2 = all(tf1,2)
i1 = find(tf2,1,'first')
tf3 = A ==-999
tf4 = all(tf3,2)
i2 = find(tf4,1,'first')
ix = i1:i2
B = A(ix,:)
You can do all this is in a single step but you'll get confused ...
  2 commentaires
Zaheer Shariff
Zaheer Shariff le 13 Août 2018
Thanks Jos. As you suggest I will study each of the steps and let you know if I still have any questions. Can you also kindly post how we can do it in a single step. As this a part of a larger code and it will be better if I can achieve this in one step. Thank you again.
Jos (10584)
Jos (10584) le 14 Août 2018
You're welcome. The single step:
B = A(find(all(isnan(A),2),1,'first'):find(all(A==-999,2),1,'first'),:)
but I strongly recommend you split it up. The one-liner won't run faster but will cause headaches when debugging later on (for instance, because you (I) may have missed a bracket ...)

Connectez-vous pour commenter.

Plus de réponses (1)

Fangjun Jiang
Fangjun Jiang le 13 Août 2018
a=[4 7
6 8
NaN NaN
0.2 0.5
0.3 0.9
0.1 0.7
0.6 0.4
-999 -999
1.6 1.9
2.8 6.4
5.1 8.3
2.3 4.7];
StartRow=find(all(isnan(a),2));
EndRow=find(all(a==-999,2));
Rows=EndRow-StartRow-1

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by