MATLAB Simplifying Matlab Programming: Need Help with Iterating for xtotal Value

  • Thread starter Thread starter tactical
  • Start date Start date
AI Thread Summary
The discussion focuses on simplifying MATLAB programming for iterating values to calculate a total, xtotal, under the constraint that the sum of four variables (i, j, k, q) equals 1. A suggested approach involves using nested for-loops to iterate through values of i, j, k, and q, checking the condition within the innermost loop. The proposed code structure includes a conditional statement to perform calculations for x1, x2, x3, and x4 only when the sum equals 1. However, it is noted that this method will significantly increase the time complexity due to the multiple nested loops. The conversation emphasizes the need for careful consideration of performance when implementing such iterations.
tactical
Messages
6
Reaction score
0
Programming in matlab. I have everything entered correctly, I just need help with iterating.
The program is similar to the following:

for i=0.1:0.99
calculates x1
for j=0.1:0.99
calculates x2
for k=0.1:0.99
calculates x3
for q=0.1:0.99
calculates x4
end
end
end
end
xtotal=x1*x2*x3*x4

I want to display all xtotal value, but the catch is I need i+j+k+q=1.
So for example i=.20,j=.25,k=.40,q=.15

TIA
 
Physics news on Phys.org
It's not quite clear, but do you want to calculate the value of x1, x2, x3 and x4 at the instant when i+j+k+q=1? In that case, use nested for-loops.
[CODE lang="matlab" highlight="5-8"]for i=0.1:0.01:0.99
for j=0.1:0.01:0.99
for k=0.1:0.01:0.99
for q=0.1:0.01:0.99
if (i + j + k + q == 1)
%calculate x1, x2, x3, x4
%calculate xtotal
end
end
end
end
end[/CODE]
But let me warn you beforehand that the time complexity of your code will significantly increase due to the four nested loops.
 
Last edited:

Similar threads

Replies
2
Views
2K
Replies
2
Views
218
Replies
0
Views
157
Replies
5
Views
3K
Replies
4
Views
2K
Replies
8
Views
2K
Back
Top