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

68 ビュー (過去 30 日間)
France Poirier
France Poirier 2021 年 1 月 19 日
コメント済み: France Poirier 2021 年 1 月 27 日
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
  1 件のコメント
France Poirier
France Poirier 2021 年 1 月 27 日
Thank you very much! Does exactly what I want. I really appreciate it!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops 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