Loop to distribute the K in Two Variables

3 views (last 30 days)
The Value of K = 1:10; Must be distributed as follows:
When K=1 is an odd number then k1=1 and k2=0.
When K=2 even number then We will split it equally k1=1 and k2=1.
When K=3 is an odd number, We will see the sum of all values in k1 and k2, and then the smallest sum which in this case k2 will take the bigger number (2) While k1 will take (1).
When K=4 even number then We will split it equally k1=2 and k2=2.
When K=5 is an odd number, We will see the sum of all values in k1 and k2, and then the smallest sum, and in this case, k1 and k2 are equal, so you can give the bigger value to anyone of them.
We will continue like this and store the values of k1 and k2
k1=[1 1 1 2 .....]
k2=[0 1 2 2 .....]

Accepted Answer

Image Analyst
Image Analyst on 5 Feb 2022
Ali, have you tried this:
K = 1 : 10;
k1 = floor(K / 2)
k1 = 1×10
0 1 1 2 2 3 3 4 4 5
k2 = K - k1
k2 = 1×10
1 1 2 2 3 3 4 4 5 5

More Answers (1)

Davide Masiello
Davide Masiello on 4 Feb 2022
Edited: Davide Masiello on 4 Feb 2022
I am slightly confused about a couple of aspects, but something like this should work
clear,clc
K = 1:10;
k0 = zeros(2,length(K));
k0(1,1) = 1;
for i = 2:length(K)
if mod(i,2) == 0
k0(:,i) = [i/2;i/2];
else
s = sum(k0,2);
k0(:,i) = flip(s);
end
end
k1 = k0(1,:)
k2 = k0(2,:)
For K = 1:10 get
k1 = [1 1 1 2 5 3 13 4 30 5]
k2 = [0 1 2 2 5 3 13 4 30 5]
  7 Comments
Davide Masiello
Davide Masiello on 5 Feb 2022
I assumed that my solution was correct from the moment that @Ali Algushti accepted the answer. So I am slightly confused by the follow up comment of @Image Analyst. Please do let me know if I have infringed some policy of the Matlab answer forum. Albeit I have been using Matlab for a while now, I have only recently started answering questions.
Walter Roberson
Walter Roberson on 5 Feb 2022
I would appreciate it if you would direct me to the documentation about which Attitudes are "Acceptable" while answering questions here.

Sign in to comment.

Categories

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

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!