Find row Index of strings in cell Array (Matlab) - arrays

If I have a cell array C:
C = {'name' 'hh' '23' [] []
'last' 'bb' '12' '8' 'hello'
'In' 'kk' '12' '2131' []
'name' 'kk' '23' [] []
'name' 'cv' '22' [] []
'name' 'ph' '23' [] [] } ;
How can I get the row index of all the rows that have 'name' in the first column and '23' in the third column?
indexresult = [1,4,6]

The simplest way to do this (all-versions compatible) would be to just use strcmp, which can accept cell arrays and does a "string compare".
One liner
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% indexresult = [1; 4; 6];
Explanation
% Get logical array of rows where first column is 'name'
logicalname = strcmp(C(:,1), 'name');
% Get logical array of rows where third column is '23'
logical23 = strcmp(C(:,3), '23');
% Get logical array where both of the above are true, using and (&)
logicalname23 = strcmp(C(:,1), 'name') & strcmp(C(:,3), '23');
% Get indices from logical array using find
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% If you wanted a row vector instead of column vector, just transpose too
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23')).';
If you want to be case insensitive (matching 'name', 'NAME', 'Name', ...) then use strcmpi instead of strcmp.

YOu can use strfind to get the indices which has string name and then use logical indices to get 23 out of the obtained indices.
C = {'name' 'hh' '23' [] []
'last' 'bb' '12' '8' 'hello'
'In' 'kk' '12' '2131' []
'name' 'kk' '23' [] []
'name' 'cv' '22' [] []
'name' 'ph' '23' [] [] } ;
% find indices of name
idx = strfind(C(:,1), 'name');
idx = find(not(cellfun('isempty', idx)));
% pick 23 from 3rc column
iwant =idx((str2double(C(idx,3))==23))

Related

column of type jsonb query by length of array in jsonb

I have a Postgres table account_summaries that has a column names of type jsonb, which has data in array form, e.g. ['test 1', 'test 2'] and by default has empty array [].
id | names
1 | []
2 | ['test 1', 'test 2']
3 | []
I can do select json_agg(names) from account_summaries and it gives me, for example.
json_agg
---------------------------------------------
[[], ["test 1", "test 2"], [], [], []]
(1 row)
Now, say I want to write a query such that:
if the names column is an empty array, return nothing
if the names column is not an empty array, return the elements in the column
the end result is a 1-dimensional array with the names
So instead I would get
json_agg
---------------------------------------------
['test 1', 'test 2']
(1 row)
I've tried
SELECT CASE WHEN cardinality(jsonb_agg(names))>0 THEN names ELSE NULL END from account_summaries;
But it doesn't work.
I'm using Postgres 11.4
with t(x) as (values('["a","b"]'::jsonb),('[]'),('["c","d"]'))
select jsonb_agg(j)
from t, jsonb_array_elements(x) as j;
jsonb_agg
----------------------
["a", "b", "c", "d"]
demo

Ruby - return boolean for matching one or both elements in an array element

I have an array that consists of strings with text separated by commas. I need to return a boolean that indicates if it is empty or if one or both of two other strings is the only value contained in the array element.
text1 = John
text2 = Doe
array1['element'] = 'John, Doe' #true
array2['element'] = 'Bob, Buck' #false
array3['element'] = 'John, Buck' #false
array4['element'] = 'John' #true
array5['element'] = 'John, John' #true
array6['element'] = '' #true
I can match one at a time or an empty element, but I'm not sure how to handle making sure only my matches are included and not other text.
foo = 'John,Doe,Buck'
if foo['John']
foo <= 'Set to Repeat'
elsif foo['Doe']
foo <= 'Set to Repeat'
elsif foo['John,Doe']
foo <= 'Set to Repeat'
elsif foo['']
foo <= 'Set to Repeat'
else foo
end
Using this code I get a match, but I need to reject it because of the presence of 'Buck'.
The question is a bit confusing because array1['element'] is invalid if array is an array. The method Array#[] must take one integer, two integers or a range as its argument(s). Giving it an argument that is a string will raise an exception (TypeError (no implicit conversion of String into Integer).
Suppose:
text = ['John', 'Doe']
arr = ['John, Doe', 'Bob, Buck', 'John , Buck', 'John', 'John, John', '']
and you wish to know which elements of arr (strings) contain only the words in the array text. You can do that as follows.
arr.map { |s| s.split(/ *, +/).all? { |ss| text.include?(ss) } }
#=> [true, false, false, true, true, true]
If, for example, s = 'Bob, Buck', then
s.split(/, +/)
#=> ["Bob", "Buck"]
Similarly,
'Bob'.split(/, +/)
#=> ["Bob"]
''.split(/, +/)
#=> []
See String#split, Array#all? and Array#include?. The regular expression / *, +/ reads, "match zero or more (*) spaces followed by a comma followed by one or more (+) spaces". (If 'John,Doe' is to be permitted use / *, */.)
Alternatively, one could write
arr.map { |s| s.split(',').all? { |ss| text.include?(ss.strip) } }
#=> [true, false, false, true, true, true]
Here
'John , Buck'.split(',')
#=> ["John ", " Buck"]
but then
"John ".strip
#=> "John"
" Buck".strip
#=> "Buck"
See String#strip.
You may wonder why I used Array#all? considering that all?'s receiver is an array containing only two elements (e.g., a = ['John', 'Doe']. It is simply because it is easier to regard a as an array of arbitrary size than to have one statement that requires text to include a[0] and another that requires text to include a[1].
Lastly, another variant would be to use String#scan:
arr.map { |s| s.scan(/[, ]+/).all? { |ss| text.include?(ss) } }
#=> [true, false, false, true, true, true]
scan takes an argument that is a regular expression that reads, "match one or more (+) characters, each of which is a character other than (^) a comma or a space". The brackets denote a character class, meaning that a character must match any character in the class. The ^ at the beginning of the class definition means "other than the characters that follow".

Match Array1 and Array2 values jQuery

I have absolutely no clue where to look for.. I have 2 arrays in jQuery and I want to combine the values together. As in: first value array one with first value array 2..
I have 2 arrays, example:
$arrayOne = 'A', 'B', 'C', 'D'
$arrayTwo = '1', '2', '3', '4'
I want to combine these and get the following output
'A': '1',
'B': '2',
'C': '3',
'D': '4',
Any help would be very much appreciated!
Danny
Approach: Loop over the array whose value you want as a key & then push one by one key value pair objects into a map object which is has to declare above the loop.
Note: Both arrays should have the same number of elements.
Code:
$arrayOne = ['A', 'B', 'C', 'D']
$arrayTwo = ['1', '2', '3', '4']
var arrayToMap = new Object(); // or var map = {};
$arrayOne.forEach(function( value, index ) {
arrayToMap[value] = $arrayTwo[index];
});
console.log(arrayToMap);
Output:
{A: "1", B: "2", C: "3", D: "4"}
You can refer the following link if you are new to the array list + loops:
https://api.jquery.com/jquery.each/

Counting and computing the average length of words in ruby

I'm trying to debug a program in ruby that is meant to compute and print the average length of words in an array.
words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers', 'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation', 'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition', 'that', 'all', 'men', 'are', 'created', 'equal']
word_lengths = Array.new
words.each do |word|
word_lengths << word_to.s
end
sum = 0
word_lengths.each do |word_length|
sum += word_length
end
average = sum.to_s/length.size
puts "The average is " + average.to_s
Obviously, the code is not working. When I run the program, I receive an error message that says the string '+' can't be coerced into fixnum (typeerror).
What do I do no make the code compute the average length of the strings in the array?
Try:
words.join.length.to_f / words.length
Explanation:
This takes advantage of chaining methods together. First, words.join gives a string of all the characters from the array:
'Fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinentanewnationconcei
vedinLibertyanddedicatedtothepropositionthatallmenarecreatedequal'
We then we apply length.to_f giving the length as a float (using a float ensures an accurate final result):
143.0
We then divide the above using / words.length:
4.766666666666667
Try this.
words = ['Four', 'score', 'and', 'seven', 'years', 'ago', 'our', 'fathers',
'brought', 'forth', 'on', 'this', 'continent', 'a', 'new', 'nation',
'conceived', 'in', 'Liberty', 'and', 'dedicated', 'to', 'the', 'proposition',
'that', 'all', 'men', 'are', 'created', 'equal']
sum = 0
words.each do |word|
sum += word.length
end
average = sum.to_i/words.size
puts "The average is " + average.to_s
You don't have to have a separate word_lengths variable to keep all the sizes of words in words array. Without looping through the word_lengths array you can merge both loops into one loop as I have given in the post.
The way you're getting the length of the word is wrong. Use word.length. See here.

Iterate over a Hash to retrieve values matching an array

I have the code -
class Conversion
hash ={'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000}
puts "enter the string"
input = gets.chomp.upcase.split(//)
result = 0
hash.each do | key, value |
case key
when 'M'
result = result + value
when 'D'
result = result + value
when 'C'
result = result + value
when 'L'
result = result + value
when 'X'
result = result + value
when 'V'
result = result + value
when 'I'
result = result + value
end
end
puts result
end
c= Conversion.new
I am giving a string like mxv through command line and converting that into an array and have it as MXV in 'input'.
Now I want to iterate over the Hash so I can get the corresponding 'values' of the keys that I have as String in my array.
For ex, for MXV , i need values = [1000, 10, 5].
How can I do that?
arr = []
"MXV".each_char do |i|
arr << hash[i.capitalize]
end
arr = [1000, 10, 5]
or
"MXV".each_char.map { |i| hash[i.capitalize] }
If you input character does not exist in hash keys
for example:
"MXVabc".each_char.map { |i| hash[i.capitalize] }
it will output:
=> [1000, 10, 5, nil, nil, 100]
you just need to use compact method.
"MXVabc".each_char.map { |i| hash[i.capitalize] }.compact
=> [1000, 10, 5, 100]
I did some more research and referred to this post on stack -
Ruby - getting value of hash
and solved my problem as -
input.each do |i|
value = hash[i.to_sym]
puts value
end
Thanks to any one who took the time to look through the question.

Resources