How to find what number is missing from a range inside of an array?

I wanted to know if there was anyway to get matlab to tell me what number was missing from an array of numbers? Kind of like a sudoku problem, I wanted to have matlab look at each row or column in an array and tell me what number from a range of numbers is missing. So, for example, if my array looks like this:
x = 5x5 array
[1 2 0 4 5
2 0 3 4 5
4 5 1 0 2
0 3 4 5 1
1 0 4 3 5]
The numbers in the array can be in any particular order, I just threw this one together for example. In this example, each row is made of elements of numbers on a range 1:5, with zero being the number that is missing from each row within that range. I know how to find all the indices outside of the range 1:5, but I wanted to know if there was a way to return what values are actually missing from each row? So, for example, I wanted to know if I can get matlab to tell me something like,
ans = 5x1 array
[3
1
3
3
2
2]
So these are the numbers that are missing from each row. Can I get matlab to do this?

 Respuesta aceptada

Example
full = [1;2;3;4;5];
sample = [2;4;5];
idx = ismember(full, sample);
full(~idx)

6 comentarios

I'm trying to apply this to the above array x and it's not returning the missing values. Could you help me better understand?
Sure, let's see what you tried so I can help fix it.
x = [1 2 0 4 5
2 0 3 4 5
4 5 1 0 2
0 3 4 5 1
1 0 4 3 5]
So first I put in the value of x
full = [1;2;3;4;5]
Then I put in the range of numbers that should be in each row
idx = ismember(x, full)
idx =
5×5 logical array
1 1 0 1 1
1 0 1 1 1
1 1 1 0 1
0 1 1 1 1
1 0 1 1 1
Then I had it check to see which were in the range of numbers
But now when I try x(~idx) or full(~idx) it doesn't return what values from the range are missing in each row.
The two input terms are in different order than in my answer. That matters!
Also, my answer works with vectors while yours contains a vector and a matrix.
ismember(A,B) returns a logical array the same size as A where "true" indicate that the elements of A are anywhere in B.
If you're performing this operation on columns of a matrix, loop through the columns so you're also working with vectors.
okay, so I need it to check each row or column individually? Like, I need to have row 1 be a vector, then row 2, then 3 etc?
If you want to know which elements in A are missing in the entire matrix, use
ismember(ColumnVector, matrix(:))
If you want to know which elements are missing in each row or column you'll need to loop through the rows/columns.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.

Productos

Versión

R2020a

Etiquetas

Preguntada:

el 24 de Sept. de 2020

Comentada:

el 24 de Sept. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by