Octave(MATLAB): Error in function on some inputs - matlab

I wrote the following function for my filter,
function filteredX=dftFilter(X,lowerBound,upperBound)
lower=max(ceil((lowerBound/(2*pi))*length(X)), 1);
upper=floor((upperBound/(2*pi))*length(X));
filteredX=zeros(1,length(X));
for int=lower:upper
filteredX(int)=X(int);
end
endfunction
If I use it for the following input, everything works correctly
dftFilter([3, 5, 7, 9, 11, 13, 12, 14, 16, 18, 20], (pi / 4), ((3 * pi) / 4))
dftFilter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ((3 * pi) / 4), (2 * pi)
but when I use it on this one (notice that the length of array is now 11 instead of 10)
dftFilter([2, 4, 6, 7, 2, 11, 23, 12, 34, 21, 17], 0, 2 * pi)
it gives an error
subscript indices must be either positive integers or logicals.
on line
filteredX(int)=X(int);
I tried to emulate this process in console.
X = [2, 4, 6, 7, 2, 11, 23, 12, 34, 21, 17];
lower=max(ceil((0/(2*pi))*length(X)), 1);
upper=floor((2*pi/(2*pi))*length(X));
filterexX=zeros(1,length(X));
for int=lower:upper;
filteredX(int)=X(int)
end
and it works fine.
PS: I'm using Octave

Print the value of int, inside your loop! You will see it is not an integer one, thus you indexing the matrix, with a real number, not an integer!

Related

Get the list of Triad nodes , who fall under the category of individual Triadic Census

By executing Networkx triadic_census Algorithm, I'm able to get the dictionary of the number of nodes falling on each type of triadic census
triad_census_social=nx.triadic_census(social_graph.to_directed())
Now, I'd like to return the list of triads, who all follow the pattern of census code "201", "120U", or any one of the 16 existing types.
How can I get those node lists under a census count?
There is no function in networkx that allow you to do it, so you should implement it manually. I modified the networkx.algorithms.triads code for you to return triads, not their count:
import networkx as nx
G = nx.DiGraph()
G.add_nodes_from([1,2,3,4,5])
G.add_edges_from([(1,2),(2,3),(2,4),(4,5)])
triad_census_social=nx.triadic_census(G)
# '003': 2,
# '012': 4,
# '021C': 3,
# '021D': 1,
# another: 0
#: The integer codes representing each type of triad.
#:
#: Triads that are the same up to symmetry have the same code.
TRICODES = (1, 2, 2, 3, 2, 4, 6, 8, 2, 6, 5, 7, 3, 8, 7, 11, 2, 6, 4, 8, 5, 9,
9, 13, 6, 10, 9, 14, 7, 14, 12, 15, 2, 5, 6, 7, 6, 9, 10, 14, 4, 9,
9, 12, 8, 13, 14, 15, 3, 7, 8, 11, 7, 12, 14, 15, 8, 14, 13, 15,
11, 15, 15, 16)
#: The names of each type of triad. The order of the elements is
#: important: it corresponds to the tricodes given in :data:`TRICODES`.
TRIAD_NAMES = ('003', '012', '102', '021D', '021U', '021C', '111D', '111U',
'030T', '030C', '201', '120D', '120U', '120C', '210', '300')
#: A dictionary mapping triad code to triad name.
TRICODE_TO_NAME = {i: TRIAD_NAMES[code - 1] for i, code in enumerate(TRICODES)}
def _tricode(G, v, u, w):
"""Returns the integer code of the given triad.
This is some fancy magic that comes from Batagelj and Mrvar's paper. It
treats each edge joining a pair of `v`, `u`, and `w` as a bit in
the binary representation of an integer.
"""
combos = ((v, u, 1), (u, v, 2), (v, w, 4), (w, v, 8), (u, w, 16),
(w, u, 32))
return sum(x for u, v, x in combos if v in G[u])
census = {name: set([]) for name in TRIAD_NAMES}
n = len(G)
m = {v: i for i, v in enumerate(G)}
for v in G:
vnbrs = set(G.pred[v]) | set(G.succ[v])
for u in vnbrs:
if m[u] <= m[v]:
continue
neighbors = (vnbrs | set(G.succ[u]) | set(G.pred[u])) - {u, v}
# Calculate dyadic triads instead of counting them.
for w in neighbors:
if v in G[u] and u in G[v]:
census['102'].add(tuple(sorted([u, v, w])))
else:
census['012'].add(tuple(sorted([u, v, w])))
# Count connected triads.
for w in neighbors:
if m[u] < m[w] or (m[v] < m[w] < m[u] and
v not in G.pred[w] and
v not in G.succ[w]):
code = _tricode(G, v, u, w)
census[TRICODE_TO_NAME[code]].add(tuple(sorted([u, v, w])))
# null triads, I implemented them manually because the original algorithm computes
# them as _number_of_all_possible_triads_ - _number_of_all_found_triads_
for v in G:
vnbrs = set(G.pred[v]) | set(G.succ[v])
not_vnbrs = set(G.nodes()) - vnbrs
for u in not_vnbrs:
unbrs = set(G.pred[u]) | set(G.succ[u])
not_unbrs = set(G.nodes()) - unbrs
for w in not_unbrs:
wnbrs = set(G.pred[w]) | set(G.succ[w])
if v not in wnbrs and len(set([u, v, w])) == 3:
census['003'].add(tuple(sorted([u, v, w])))
# '003': {(1, 3, 4), (1, 3, 5)},
# '012': {(1, 2, 3), (1, 2, 4), (2, 3, 4), (2, 4, 5)},
# '021C': {(1, 2, 3), (1, 2, 4), (2, 4, 5)},
# '021D': {(2, 3, 4)},
# another: empty
Building on vurmux's answer (by fixing the '102' and '012' triads):
import networkx as nx
import itertools
def _tricode(G, v, u, w):
"""Returns the integer code of the given triad.
This is some fancy magic that comes from Batagelj and Mrvar's paper. It
treats each edge joining a pair of `v`, `u`, and `w` as a bit in
the binary representation of an integer.
"""
combos = ((v, u, 1), (u, v, 2), (v, w, 4), (w, v, 8), (u, w, 16),
(w, u, 32))
return sum(x for u, v, x in combos if v in G[u])
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4, 5])
G.add_edges_from([(1, 2), (2, 3), (2, 4), (4, 5)])
#: The integer codes representing each type of triad.
#: Triads that are the same up to symmetry have the same code.
TRICODES = (1, 2, 2, 3, 2, 4, 6, 8, 2, 6, 5, 7, 3, 8, 7, 11, 2, 6, 4, 8, 5, 9,
9, 13, 6, 10, 9, 14, 7, 14, 12, 15, 2, 5, 6, 7, 6, 9, 10, 14, 4, 9,
9, 12, 8, 13, 14, 15, 3, 7, 8, 11, 7, 12, 14, 15, 8, 14, 13, 15,
11, 15, 15, 16)
#: The names of each type of triad. The order of the elements is
#: important: it corresponds to the tricodes given in :data:`TRICODES`.
TRIAD_NAMES = ('003', '012', '102', '021D', '021U', '021C', '111D', '111U',
'030T', '030C', '201', '120D', '120U', '120C', '210', '300')
#: A dictionary mapping triad code to triad name.
TRICODE_TO_NAME = {i: TRIAD_NAMES[code - 1] for i, code in enumerate(TRICODES)}
triad_nodes = {name: set([]) for name in TRIAD_NAMES}
m = {v: i for i, v in enumerate(G)}
for v in G:
vnbrs = set(G.pred[v]) | set(G.succ[v])
for u in vnbrs:
if m[u] > m[v]:
unbrs = set(G.pred[u]) | set(G.succ[u])
neighbors = (vnbrs | unbrs) - {u, v}
not_neighbors = set(G.nodes()) - neighbors - {u, v}
# Find dyadic triads
for w in not_neighbors:
if v in G[u] and u in G[v]:
triad_nodes['102'].add(tuple(sorted([u, v, w])))
else:
triad_nodes['012'].add(tuple(sorted([u, v, w])))
for w in neighbors:
if m[u] < m[w] or (m[v] < m[w] < m[u] and
v not in G.pred[w] and
v not in G.succ[w]):
code = _tricode(G, v, u, w)
triad_nodes[TRICODE_TO_NAME[code]].add(
tuple(sorted([u, v, w])))
# find null triads
all_tuples = set()
for s in triad_nodes.values():
all_tuples = all_tuples.union(s)
triad_nodes['003'] = set(itertools.combinations(G.nodes(), 3)).difference(all_tuples)
Result
# print(triad_nodes)
# {'003': {(1, 3, 4), (1, 3, 5)},
# '012': {(1, 2, 5), (1, 4, 5), (2, 3, 5), (3, 4, 5)},
# '102': set(),
# '021D': {(2, 3, 4)},
# '021U': set(),
# '021C': {(1, 2, 3), (1, 2, 4), (2, 4, 5)},
# '111D': set(),
# '111U': set(),
# '030T': set(),
# '030C': set(),
# '201': set(),
# '120D': set(),
# '120U': set(),
# '120C': set(),
# '210': set(),
# '300': set()}
In agreement with nx.triadic_census
# print(nx.triadic_census(G))
# {'003': 2,
# '012': 4,
# '102': 0,
# '021D': 1,
# '021U': 0,
# '021C': 3,
# '111D': 0,
# '111U': 0,
# '030T': 0,
# '030C': 0,
# '201': 0,
# '120D': 0,
# '120U': 0,
# '120C': 0,
# '210': 0,
# '300': 0}

Spark - Remove intersecting elements between two array type columns

I have dataframe like this
+---------+--------------------+----------------------------+
| Name| rem1| quota |
+---------+--------------------+----------------------------+
|Customer_3|[258, 259, 260, 2...|[1, 2, 3, 4, 5, 6, 7,..500]|
|Customer_4|[18, 19, 20, 27, ...|[1, 2, 3, 4, 5, 6, 7,..500]|
|Customer_5|[16, 17, 51, 52, ...|[1, 2, 3, 4, 5, 6, 7,..500]|
|Customer_6|[6, 7, 8, 9, 10, ...|[1, 2, 3, 4, 5, 6, 7,..500]|
|Customer_7|[0, 30, 31, 32, 3...|[1, 2, 3, 4, 5, 6, 7,..500]|
I would like to remove list value in rem1 from quota and create as one new column. I have tried.
val dfleft = dfpci_remove2.withColumn("left",$"quota".filter($"rem1"))
<console>:123: error: value filter is not a member of org.apache.spark.sql.ColumnName
Please advise.
You can use a filter in a column in such way, you can write an udf as below
val filterList = udf((a: Seq[Int], b: Seq[Int]) => a diff b)
df.withColumn("left", filterList($"rem1", $"quota") )
This should give you the expected result.
Hope this helps!

Do you have any idea or documentation about why we have arc4random_stir() in swift?

I have written the program below for generating random unique numbers for several number of times by invoking the function, but it seems like I'm getting the same pattern with minimal changes.
func generateRandom(withinNumber: Int) {
var i:Int = 0
var elements = Set<Int>()
while i != withinNumber {
let num:Int = Int(arc4random())%withinNumber + 1
if elements.count <= withinNumber && elements.contains(num) == false {
elements.insert(num)
}
else {
i = i-1
}
i=i+1
}
print(elements)
elements.removeAll()
}
generateRandom(withinNumber: 10)
How does I make my program effectively run to generate several random unique numbers.
Please let me know it would be very helpful for me.
You are storing your numbers in a Set and sets are not ordered, so the order the elements are shown by print is unrelated to the order in which they were added to the set.
Rather the elements of a set are stored in some manner which enables fast checking for .contains(), and this is one reason you seeing similar sequences.
If you wish to preserve order of insertion use a collection which does this, i.e. an array. Changing to an array in your code produced the following results from 9 calls:
[8, 9, 7, 10, 5, 6, 2, 3, 1, 4]
[4, 9, 10, 3, 6, 2, 1, 7, 8, 5]
[8, 3, 5, 1, 6, 4, 9, 10, 7, 2]
[5, 7, 2, 9, 8, 1, 6, 10, 3, 4]
[2, 3, 7, 6, 9, 1, 8, 10, 5, 4]
[9, 10, 2, 4, 6, 8, 5, 7, 1, 3]
[9, 10, 2, 5, 4, 7, 3, 8, 1, 6]
[1, 6, 4, 5, 8, 2, 3, 9, 7, 10]
[6, 10, 5, 3, 2, 8, 1, 9, 7, 4]
You are also generating 10 random numbers in the range 1 to 10 and avoiding duplicates, so the results is always going to be the numbers 1 to 10 in some order.
To generate a random number in a given range do not use %, instead use the provided arc4random_uniform() which will give better a better distribution.
The function mention in your title arc4random_stir() is available in Swift.
BTW (somewhat opinion based): It is better to write !e (! being the boolean not operator) rather than e == false, and never ever write e == true which is the long form of e!
BTW (SO etiquette): Don't link to your code (or paste in images of it). Reduce to a small example which demonstrates the issue (not required in your case) and insert directly in the question. Keep tags minimal and appropriate. These edits were done for you this time by myself and others, you will know for next time.
HTH

Unable to replicate shuffle in a array in Swift

I have two arrays that I want to shuffle. These are the two arrays:
var allCards = ["2_of_clubs", "2_of_spades", "2_of_diamonds", "2_of_hearts", "3_of_clubs", "3_of_spades", "3_of_diamonds", "3_of_hearts", "4_of_clubs", "4_of_spades", "4_of_diamonds", "4_of_hearts", "5_of_clubs", "5_of_spades", "5_of_diamonds", "5_of_hearts", "6_of_clubs", "6_of_spades", "6_of_diamonds", "6_of_hearts", "7_of_clubs", "7_of_spades","7_of_diamonds","7_of_hearts", "8_of_clubs", "8_of_spades", "8_of_diamonds", "8_of_hearts", "9_of_clubs", "9_of_spades", "9_of_diamonds", "9_of_hearts", "10_of_clubs", "10_of_spades", "10_of_diamonds", "10_of_hearts", "jack_of_clubs", "jack_of_spades", "jack_of_diamonds", "jack_of_hearts", "queen_of_clubs", "queen_of_spades", "queen_of_diamonds", "queen_of_hearts", "king_of_clubs", "king_of_spades", "king_of_diamonds", "king_of_hearts", "ace_of_clubs", "ace_of_spades", "ace_of_diamonds", "ace_of_hearts"]
var allValues = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14]
I want to shuffle them equally, so value 2 stays at 2 of clubs, 2 of spades and so on. I tried using the answers from Shuffle array swift 3 and How do I shuffle an array in Swift? they stated this should work:
let randomIndex = UInt64(arc4random_uniform(UInt32(1000)))
let randomShuffle = GKLinearCongruentialRandomSource(seed: randomIndex)
let shuffledValues = randomShuffle.arrayByShufflingObjects(in: allValues)
let shuffledCards = randomShuffle.arrayByShufflingObjects(in: allCards)
print(shuffledValues)
print(shuffledCards)
I get this as a print:
[3, 6, 5, 5, 9, 10, 11, 11, 8, 6, 5, 3, 14, 12, 3, 8, 2, 3, 10, 4, 13, 12, 7, 12, 10, 5, 12, 13, 14, 11, 2, 6, 9, 7, 10, 14, 7, 8, 6, 14, 4, 9, 13, 2, 11, 9, 4, 7, 8, 2, 13, 4]
[jack_of_clubs, 6_of_hearts, 10_of_hearts, 6_of_spades, king_of_hearts, 5_of_spades, 5_of_hearts, ace_of_diamonds, queen_of_diamonds, 10_of_spades, 7_of_hearts, queen_of_spades, 9_of_clubs, 2_of_diamonds, 3_of_hearts, 3_of_diamonds, 9_of_spades, queen_of_clubs, 8_of_clubs, 9_of_diamonds, 7_of_clubs, 3_of_spades, 8_of_spades, 8_of_hearts, 5_of_clubs, 6_of_diamonds, ace_of_spades, 2_of_spades, ace_of_clubs, 10_of_diamonds, 4_of_spades, 2_of_clubs, 10_of_clubs, king_of_diamonds, 7_of_diamonds, 6_of_clubs, 8_of_diamonds, queen_of_hearts, 9_of_hearts, jack_of_diamonds, 2_of_hearts, king_of_clubs, jack_of_spades, 4_of_hearts, 7_of_spades, 3_of_clubs, 4_of_diamonds, 4_of_clubs, king_of_spades, jack_of_hearts, ace_of_hearts, 5_of_diamonds]
Both have the same count. I am curious why this does not work. Is it possible to edit this code to make it work, else I would like to know how to shuffle an array and replicate that.
You can pair up your elements with zip, then shuffle, then unzip.
let pairs = Array(zip(allCards, allValues))
let randomIndex = UInt64(arc4random_uniform(UInt32(1000)))
let randomShuffle = GKLinearCongruentialRandomSource(seed: randomIndex)
let shuffledPairs = randomShuffle.arrayByShufflingObjects(in: pairs) as! [(String, Int)]
let shuffledCards = shuffledPairs.map { $0.0 }
let shuffledValues = shuffledPairs.map { $0.1 }

illegal division by zero:Perl

I have written a code to find determinant of a 10X10 matrix. This code gives the proper result till 9X9 matrix. But for 10X10 matrix gives the following error
"Use of Uninitialized value in multiplication <*> at line 23
Illegal division by zero at line 21"
I tried for 11X11 matrix also, but it is giving the wrong answer.
Why this code is giving such error...
Following is the code:
#!/usr/bin/perl
use strict;
use warnings;
my #x1=(
[5, 6, 3, 2, 4, 9, 3, 5, 4, 2],
[12, 9, 8, 3, 3, 0, 6, 9, 3, 4],
[8, 6, 5, 8, 9, 3, 9, 3, 9, 5],
[6, 4, 3, 0, 6, 4, 8, 2, 22, 8],
[8, 3, 2, 5, 2, 12, 7, 1, 6, 9],
[5, 9, 3, 9, 5, 1, 3, 8, 4, 2],
[3, 10, 4, 16, 4, 7, 2, 12, 9, 6],
[2, 12, 9, 13, 8, 3, 1, 16, 0, 6],
[3, 6, 8, 5, 12, 8, 4, 19, 8, 5],
[2, 5, 6, 4, 9, 10, 3, 11, 7, 3]
);
# Matrix of nxn
for (my $i=0;$i le 9;$i++) {
for (my $j=0;$j le 9;$j++) {
if($j>$i) {
my $ratio = $x1[$j][$i]/$x1[$i][$i];
for(my $k = 0; $k le 9; $k++){
$x1[$j][$k] -= $ratio * $x1[$i][$k];
}
}
}
}
my $det1 = 1;
for(my $i = 0; $i le 9; $i++){
$det1 *= $x1[$i][$i];
}
printf $det1," ";
le doesn't do what you think it does. http://perldoc.perl.org/perlop.html
Binary "le" returns true if the left argument is stringwise less than or equal to the right argument.
print 10 le 9,"\n";
print 10 <= 9,"\n";
It's a stringwise comparison not a numeric one.
So "10" le "9" is true, because alphabetically 10 is before 9.
But this would work fine for a smaller matrix, because 9 le 8 is a valid comparison and works the 'right way'.
You should use <= instead:
Binary "<=" returns true if the left argument is numerically less than or equal to the right argument.
You can also probably auto-scale by using $#x1 for your comparison, which is the value of the last array index. In your example above, $#x1 is 9, because your array is 0-9