How can i rewrite this logic for n elements?

if q(1,1) == 1
disp("q1 is selected")
D = D1;
P= P1;
elseif q(1,2) == 1
disp("q2 is selected")
D = D2;
P= P2;
elseif q(1,3) == 1
disp("q3 is selected")
D = D3;
P= P3;
end
Hello I have to re-write this logic for 10elements i.e what if q array consists of 1*10 slots unlike above i have just 3. also it is very unpredictable that when the value of q elements can be 1.

4 commentaires

Torsten
Torsten le 28 Fév 2023
Modifié(e) : Torsten le 28 Fév 2023
Exactly one of the q(1,:) equals 1 ? Or could there be several ? Or none ?
Sumanth
Sumanth le 28 Fév 2023
yes
Torsten
Torsten le 28 Fév 2023
yes to what ?
Sumanth
Sumanth le 28 Fév 2023
exactly one of the q values = 1.

Connectez-vous pour commenter.

 Réponse acceptée

Walter Roberson
Walter Roberson le 28 Fév 2023
Modifié(e) : Walter Roberson le 28 Fév 2023
Or...
Dvals = [D1, D2, D3, D4, D5, D6, D7, D8, D9, D10];
Pvals = [P1, P2, P3, P4, P5, P6, P7, P9, P9, P10];
idx = find(q == 1, 1); %first
if ~isempty(idx)
D = Dvals(idx);
P = Pvals(idx);
else
uh oh
end

3 commentaires

Sumanth
Sumanth le 28 Fév 2023
The code seems right but doesnt work when D1,...D10 or P1,..P10 are arrays not single values.
John D'Errico
John D'Errico le 28 Fév 2023
@Sumanth So then learn to use arrays in their many forms, possibly multidimensional arrays, or cell arrays.
Dvals = {D1, D2, D3, D4, D5, D6, D7, D8, D9, D10};
Pvals = {P1, P2, P3, P4, P5, P6, P7, P9, P9, P10};
idx = find(q == 1, 1); %first
if ~isempty(idx)
D = Dvals{idx};
P = Pvals{idx};
else
uh oh
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Operators and Elementary Operations dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by