Find the first appearance of a number in a row.

Hi I have a matrix A from which I need to return a vector which contain the index of first occurence of a number say 2030 such that we get the matrix below
A = [0 0 0 2095 3030
0 2030 2030 2030 2030
0 0 2095 2055 2065
2065 2055 2050 2030 2030]
B=[5 2 0 4]
I tried using
for i=1:4
d=A(i,:);
targetval = 2030;
num_wanted = 2030;
xx=(find(d==targetval, num_wanted, 'first'))
end
which apparently does the job (inefficiently) , but I am confused on how to store the indices in a vector and if the value (2030) is not there in a row - then return 0.

 Réponse acceptée

Voss
Voss le 28 Sep 2023
Modifié(e) : Voss le 28 Sep 2023
A = [0 0 0 2095 2030
0 2030 2030 2030 2030
0 0 2095 2055 2065
2065 2055 2050 2030 2030]
A = 4×5
0 0 0 2095 2030 0 2030 2030 2030 2030 0 0 2095 2055 2065 2065 2055 2050 2030 2030
targetval = 2030;
n_rows = size(A,1);
B = zeros(1,n_rows); % pre-allocate vector B with a zero for each row of A.
for i = 1:n_rows
d = A(i,:);
idx = find(d==targetval, 1, 'first'); % find the first occurrence of targetval in row i.
if ~isempty(idx) % if there is one, store it as element i of B;
B(i) = idx; % (otherwise element i of B remains 0).
end
end
disp(B);
5 2 0 4

4 commentaires

Voss
Voss le 28 Sep 2023
Note that the second argument of find() is the number of occurrences you want to find, not the number you want to find, so it's 1 here because you want to find only one (the first).
Here's another way, still using find(), but without the loop, applying find() to the entire matrix A at once.
A = [0 0 0 2095 2030
0 2030 2030 2030 2030
0 0 2095 2055 2065
2065 2055 2050 2030 2030]
A = 4×5
0 0 0 2095 2030 0 2030 2030 2030 2030 0 0 2095 2055 2065 2065 2055 2050 2030 2030
targetval = 2030;
B = zeros(1,size(A,1));
[rows,cols] = find(A == targetval);
[rr,ii] = unique(rows);
B(rr) = cols(ii);
disp(B);
5 2 0 4
SChow
SChow le 28 Sep 2023
Thanks, much much appreciated.
Voss
Voss le 28 Sep 2023
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Question posée :

le 28 Sep 2023

Commenté :

le 28 Sep 2023

Community Treasure Hunt

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

Start Hunting!

Translated by