Prev: Problem to choose weighting function in Robust Control/H infinity
Next: cellfun vs directly passing as an argument
From: Ruben on 29 Jun 2010 05:42 Dear all, I would like to know if there's a function that could help me to determine if there is a loop given a sequence of numbers in a vector. And also return the values creating the loop. For instance: A = [7 6 2 1 3 4 8 1 2 4 8 1 ....] B = [1 2 1 2 1 2 ...] C = [1 2 3 4 5 6 7 8 ...] The function should return something like this: is_loop(A) => loop = [1 2 4 8] is_loop(B) => loop = [1 2] is_loop(C) => loop = [] I thougth of using strings to do this but I didn't find any suitable function. Any suggestions? Thank you :-)
From: Jan Simon on 29 Jun 2010 07:48 Dear Ruben, > I would like to know if there's a function that could help me to determine if there is a loop given a sequence of numbers in a vector. And also return the values creating the loop. For instance: > > A = [7 6 2 1 3 4 8 1 2 4 8 1 ....] > The function should return something like this: > is_loop(A) => loop = [1 2 4 8] Please explain, why and how A leads to [1,2,4,8]. How do you define a "loop"? If you define the problem exactly, the way to program it should be done to 90% already. Good luck, Jan
From: Ruben on 29 Jun 2010 08:07 Sorry, my bad! I should have written A = [7 6 2 1 3 4 8 1 3 4 8 1 ....] is_loop(A) => loop = [1 3 4 8] "Jan Simon" <matlab.THIS_YEAR(a)nMINUSsimon.de> wrote in message <i0cmhk$1hc$1(a)fred.mathworks.com>... > Dear Ruben, > > > I would like to know if there's a function that could help me to determine if there is a loop given a sequence of numbers in a vector. And also return the values creating the loop. For instance: > > > > A = [7 6 2 1 3 4 8 1 2 4 8 1 ....] > > The function should return something like this: > > is_loop(A) => loop = [1 2 4 8] > > Please explain, why and how A leads to [1,2,4,8]. > How do you define a "loop"? > If you define the problem exactly, the way to program it should be done to 90% already. > > Good luck, Jan
From: Ruben on 29 Jun 2010 08:11
In fact, I just tried to simplify the problem when I posted it. What I really need to do is to find loops given a source point and a set of senders and receivers (like in network loops). An example is: [path, loop] = is_loop(2, [2,1,3,4,8,7,9], [1,3,4,8,7,9,4]) path = 2 1 3 4 8 7 9 loop = 4 8 7 9 The code is the following, but I was wondering if I could write this code in a more efficient way: function [path, loop] = is_loop(source, senders, receivers) next = source; path = []; pos = []; while (~isempty(next) && isempty(pos)) %- Check if next element is already in the path pos = find(path == next, 1, 'first'); %- Update path = [path, next]; next = receivers(senders == next); end if (~isempty(pos)) path = path(1:end-1); loop = path(pos:end); end |