How to find the first zero element in any column of a m by n matrix

66 visualizaciones (últimos 30 días)
Hi,
I have a loop that updates certain rows of an MxN matrix depending on certain conditions. At each iteration of the loop I need to find the first empty cell in each row and fill in the matrix from that point on. The problem is that the first zero element is in different locations in each row. I can't figure out how do to this without looping over rows which I want to avoid since the matix is big and it takes forever.
The basic code is something like this where C is the MxN matrix that I want to fill in:
for a = 1:10
A = find(B >= a);
B = find(C(A) == 0);
C(A(B)) = x;
The problem is that the B is a 1byT array that I don't know how to get back to the same dimensions of my original matrix to make the allocation.
Any suggestions are very much appreciated.
Thank you,
  1 comentario
dpb
dpb el 19 de En. de 2021
What is B on entry into the loop?
Is the test for A actually for the loop variable a, 1:10? It's OK if it is, just checking that's really intended, not something else.
What you want filled in the array C is not totally clear -- is this filling in every row from one point on on a row-by-row basis or globally dependent upon the magnitude of a for each step?
What is x? Is if fixed or does it change also?
I think we need to see a sample problem with inputs and the expected output to decipher this precisely enough to have a chance to write code.

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 19 de En. de 2021
Editada: Matt J el 19 de En. de 2021
I don't understand what your posted code is trying to accomplish, but you can find the first zero in each row without looping as follows,
C=randi([0,10],10,5) %example
C = 10×5
10 7 3 2 9 0 5 5 3 4 3 0 8 5 2 2 0 9 10 5 5 10 0 10 6 9 10 0 3 3 5 6 5 9 10 0 7 4 9 6 8 0 7 1 6 6 3 4 2 6
[val,location]=max(C==0,[],2);
location(val==0)=nan
location = 10×1
NaN 1 2 2 3 3 NaN 1 2 NaN

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by