Loops with multiple conditions

1 view (last 30 days)
Sydney Carrow
Sydney Carrow on 17 Mar 2021
Answered: Dave B on 17 Mar 2021
I am creating a digital copolymer chain. The index is 1:30 and if the last index was A and the random number is <=0.5, the new index should be the A. If the random number is >0.5 then the new index shoud be B. The code I have isn't working and I am not sure what to do. Thank you for the help.
%chain 1
A=zeros(30,2);
B=zeros(30,2);
for i=1:30
if A(i,1)==i || rand<=0.5
A(i,2)=1;
A(i,1)=i;
else
B(i,1)=i;
B(i,2)=1;
if B(i,1)==i || rand<=0.5
A(i,1)=i;
A(i,2)=1;
else
B(i,1)=i;
B(i,2)=1;
end
end
end
%Deletes all zeros in A
TestForZero = A(:,1) == 0;
A(TestForZero, :) = []
%Deletes all zeros in B
TestForZero = B(:,1) == 0;
B(TestForZero, :) = []
%graphs
hold on
plot(A(:,1),A(:,2),'o','MarkerFaceColor',"red",'MarkerSize',15)
plot(B(:,1),B(:,2),'o','MarkerFaceColor',"blue",'MarkerSize',15)
title("Digital Copolymerchain 4")
axis off
hold off
%Deletes all zeros in A
TestForZero = A(:,1) == 0;
A(TestForZero, :) = []
%Deletes all zeros in B
TestForZero = B(:,1) == 0;
B(TestForZero, :) = []
%graphs
hold on
plot(A(:,1),A(:,2),'o','MarkerFaceColor',"red",'MarkerSize',15)
plot(B(:,1),B(:,2),'o','MarkerFaceColor',"blue",'MarkerSize',15)
title('Digital Colymerchain 1')
axis off
hold off

Answers (1)

Dave B
Dave B on 17 Mar 2021
I'm struggling a little to understand your goal, I've coded up what you described (as I read it), but I suspect I'm missing something as your text doesn't quite make sense. Nonetheless, I noticed some potential bugs in your code if it's helpful:
  • you're generating two random numbers in your loop, which seems odd,
  • your logic statements don't seem to match your code - you wrote AND which would be represented as && but coded OR which is ||.
Feel free to clarify and I'm happy to take another attempt...the more you can simplify your question the easier it will be to help.
Here's my attempt to interpret as code based on your text:
Your text is missing one condition...
  • If the last index was A and the random number is <=0.5, the new index should be the A.
  • If the random number is >0.5 then the new index shoud be B.
You haven't accounted for the case where the last index was B, which implies a 'neither' state?
You also depend on the 'last' index, but that would mean you need some intial value. I'll make the initial value of A based on rand <= 0.5.
isA = false(1,30);
isB = false(1,30);
isA(1) = rand <= 0.5; % need some initial value as all remaining values depend on previous values
isB(1) = false;
for i = 2:30
r = rand;
if isA(i-1) && r <= 0.5
% If the last index was A *AND* the random number is <=0.5, the new index should be the A.
isA(i) = true;
elseif r>0.5
% If the random number is >0.5 then the new index shoud be B.
isB(i) = true;
end
end

Community Treasure Hunt

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

Start Hunting!