필터 지우기
필터 지우기

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

조회 수: 31 (최근 30일)
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
dpb
dpb 2021년 1월 19일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2021년 1월 19일
편집: Matt J 2021년 1월 19일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by