# Number of Elements Between 2 Elements in a matrix.

4 vues (au cours des 30 derniers jours)
s.v. le 2 Fév 2018
Say I have a 3x5 matrix of zeros.
M = zeros(3,5)
00000
00000
00000
I change two elements in the matrix so the following happens.
M(1,3) = 1
M(3,3) = 2
00100
00000
00200
How do I count the number of elements between "1" and "2"?
Like below, it would be 11 elements within the brackets.
00[100
00000
002]00
As little lines of code as possible would be appreciated! Thank you.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Star Strider le 2 Fév 2018
MATLAB uses column-major ordering, so it ‘counts’ elements column-wise, and it is necessary to transpose ‘M’ to do what you want.
M = zeros(3,5);
M(1,3) = 1;
M(3,3) = 2;
idx = find(M');
Result = diff(idx)+1
Result =
11
These can be combined into a one-line assignment:
Result = diff(find(M'))+1
It is necessary to add 1, because diff does not take into account the initial or final element when it does its subtraction.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (1)

James Tursa le 2 Fév 2018
Modifié(e) : James Tursa le 2 Fév 2018
Assuming the matrix has exactly two nonzero entries:
f = find(M'); % Transpose to get the row data into column order
result = f(2) - f(1) + 1;
If you can't guarantee that there are exactly two nonzero entries, then you will have to add in appropriate checks etc and tell us what you would want for a result in that case.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

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

### Community Treasure Hunt

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

Start Hunting!

Translated by