I'm trying to write 5 for loop cycles with a step
Afficher commentaires plus anciens
Hello, I would like to know how could I write 5 loop cycle with a step that resolve the following problem. I have 3 vectors p1,p2,p3 that increments, from 0 to 1, with a step of 0.25. Also, I have 2 parameters (b, errore) that increments with a different step b = [0:0.4:2] ed errore = [0.4:0.3:1.5]. The sum of p1,p2,p3 must be 1 in order to get b and err parameters
I would like to have some different combination of the 5 parameters (p1,p2,p3,b,errore) so that:
- p1 + p2 + p3 = 1 --> b = 0 , errore = 0.4 with p1=0.25, p2=0.5, p3=0.25 (it's just an example) --> then I would like to save these 5 parameters in the empty arrays.
- p1 + p2 + p3 = 1 --> b = 0 , errore = 0.7 with p1=0.25, p2=0.5, p3=0.25
And so on for every step increment of every combination of p1,p2,p3 possible. In this case, I would get a matrix like this:

How can I do it in a smart way? I'm pretty new to MATLAB so I'm still learning
p1= [0 0 0 0];
p2= [0 0 0 0];
p3= [0 0 0 0];
b = [0 0 0 0 0 0];
errore = [0 0 0 0];
A=zeros(25,25)
for i=1:4
p1 = p1 + 0.25;
for j=1:4
p2 = p2 + 0.25;
for k=1:4
p3 = p3 + 0.25;
if p1+p2+p3 == 1
for l=1:6
b(l)=b(l)+0.4;
x(:,l)=b(l);
elseif p1(i)+p2(i)+p3(i) > 1
warning('sum exceeding 1')
else
p3 = p3 + 0.25;
end
end
end
end
2 commentaires
Dyuman Joshi
le 19 Mai 2023
Do you want to save all the values of b and errore for every (p1, p2, p3) whose sum is equal to 1?
%p1 p2 p3 b errore
[0.25 0.25 0.5 0 0.4;
0.25 0.25 0.5 0 0.7;
0.25 0.25 0.5 0 1; ...
...
0.25 0.25 0.5 0.4 0.4
0.25 0.25 0.5 0.4 0.7;
0.25 0.25 0.5 0.4 1; ...
%and so on, like this
riki
le 19 Mai 2023
Réponse acceptée
Plus de réponses (1)
Vectorization ftw!
%Define variables
b = [0:0.4:2];
errore = [0.4:0.3:1.5];
%To obtain the combination according to the condition
%define p1, p2, p3 as grids
[p1, p2, p3] = meshgrid(0:0.25:1);
%Indices to for which the sum is equal to 1
idx = find(p1+p2+p3==1);
%Corresponding combinations
[E, B, IDX] = ndgrid(errore, b, idx);
IDX = IDX(:);
%Output
out = [p1(IDX) p2(IDX) p3(IDX) B(:) E(:)];
disp(out)
Catégories
En savoir plus sur Loops and Conditional Statements 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!