How to use matlab to write code with multiple loops?

I want to use genetic algorithm to solve such a problem, but I don't know how to construct the objective function and constraint conditions
My code is as follows. I have many bugs due to my poor level. I also hope that the leaders can give me some advice.
My main problem is that I don't know how to write the objective function and constraint conditions. Please give me some advice

2 Comments

If P and x are both arrays, then "the MATLAB way" is to use vectorized operations --
y=sum(P.*x,'all)';
I don't follow the intent with the second; the index 101 would be outside the array bounds of 1:100 given; and doesn't seem to match up with the handwritten equations anyway...
The way I like to think about nested for loop is this:
Suppose, you have a 2D matrix and you need to double the value for every element (you really don't need a for loop to do that, but this is an easy example to understand the basis of it).
A = rand(5,6)
A = 5×6
0.3389 0.9967 0.6824 0.6811 0.2735 0.5952 0.1721 0.4003 0.6431 0.8428 0.1450 0.2142 0.2188 0.6239 0.1814 0.0449 0.5347 0.7484 0.4476 0.7640 0.9599 0.9531 0.7196 0.9385 0.3933 0.7820 0.9826 0.4457 0.2284 0.6340
for i = 1:size(A,1) % it is ready to change the values for every elements of row 1
for j = 1:size(A,2) % when i = 1, it will change the values for all columns of row 1 and the loop continues
A(i,j) = 2*A(i,j);
end
end
A
A = 5×6
0.6777 1.9934 1.3649 1.3621 0.5470 1.1903 0.3443 0.8005 1.2863 1.6856 0.2900 0.4284 0.4376 1.2479 0.3627 0.0899 1.0694 1.4968 0.8953 1.5281 1.9197 1.9061 1.4392 1.8769 0.7866 1.5640 1.9652 0.8915 0.4567 1.2679

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 5 Mar 2023

Commented:

on 15 Mar 2023

Community Treasure Hunt

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

Start Hunting!