Info
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
"while" loop is not doing well..
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
hi, i'm new in matlab so i hope my question is not very stupid. i have a vector with no repetitions and i want to put inside repetitions in random chosen places. a = the vector with the no repetitions, size- 1*60 b = vector with the random spots i want to put in a repetition.
i used this code-
for i = 1:size(b,2);
a(1,b(1,i)) = a(1,(b(1,i))-1);
end
but i needed to make sure that- - i wont choose 2 consecutive spots (because i cant have 3 numbers in a row, only 2) - the chosen spot wont have the same number ahead and followed (same reason) - one of the chosen spots wont be 1 (because it will go to a(1,0))
c=vector with the number of consecutive spots if there are some. (i used the diff function and then the find function to find diff=1
then i tried using the while function- for
i = 1:size(b,2);
if b(1,i)<60
while size(c,2)>0 || b(1,i) ==1 || a(1,(b(1,i))-1) ==a(1,(b(1,i))+1)
b = randperm(60,12);
sort_b = sort(b);
b_diff = diff(sort_b);
c = find(b_diff(1,:)==1);
end
end
end
i'm still getting a 3 in a row chosen spots.. i think for some reason my while function is written incorrect.. can someone track the problem?
thank you
2 Commenti
Image Analyst
il 9 Gen 2015
Can you give an actual numerical example or what's allowed and not allowed?
dpb
il 10 Gen 2015
Firstly, a comment on coding style. It would be much easier reading the code if for 1D vectors you didn't carry around the superfluous '1', dimension. It isn't wrong, but having to figure out what the indexing is doing is more complex than needs be when there is only one dimension.
For example, your first loop of
for i = 1:size(b,2);
a(1,b(1,i)) = a(1,(b(1,i))-1);
end
can be written as
for i = 1:length(b);
a(b(i)) = a(b(i)-1);
end
also removing a set of superfluous parenthesis in the RHS indexing expression. Now that's simple-enough to see that you don't need a loop at all--
a(b)=a(b-1);
does the rearrangement in "one swell foop".
Now on to the question you asked...can you describe in words what it is the end result is that you're looking for as a general problem statement rather than worrying about the implementation details? Then, can probably work out a better solution plus will make understanding what it was you were trying to accomplish with the loop as written more comprehensible. Right now we don't understand the intent...
Risposte (0)
Questa domanda è chiusa.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!