Ruby how to compare 2D arrays values - arrays

I have two question about array of arrays on Ruby :
first, i dont know how to compare this array of arrays
a = [[1,2,3,5] , [1,2,3,6]]
(Output: 11 < 12 )
second , I want to merge them into one long array
a = [[1,2,3] , [4,5,6]]
=> a = [1,2,3,4,5,6]
Thank you.

To get an item with max sum from array you can use this line:
a.max_by {|arr| arr.inject(0, &:+)}
And to get all uniq values from all arrays in parent array, use this line:
[[1,2,3] , [4,5,6]].flatten.uniq

Your first question: Are you trying to compare the sums of the contents of your two arrays? If so you could do the following:
a = [[1,2,3,5],[1,2,3,6]]
a[0].inject(:+) < a[1].reduce(:+)
# returns true
Your second question: a.flatten will combine all of the elements into one array.
I'd recommend reading through the Ruby docs, as things like inject and flatten are explained in great detail.

first , i dont know how to compare this array of arrays a = [[1,2,3,5] , [1,2,3,6]] (try to get the answer 11 < 12 )
You could do it by using
a = [[1,2,3,5] , [1,2,3,6]]
a[0].inject{|sum,x| sum + x } < a[1].inject{|sum,x| sum + x }
Or
a = [[1,2,3,5] , [1,2,3,6]]
a[0].reduce(:+) < a[1].reduce(:+)
You could also use a[0].inject(:+) < a[1].inject(:+). Reduce emphasises Map reduce verbage.
second , i want to merge them into one long array a = [[1,2,3] , [4,5,6]] => a = [1,2,3,4,5,6]
a = [[1,2,3,5] , [1,2,3,6]]
concatenated = a.flatten
or
a = [[1,2,3,5] , [1,2,3,6]]
concatenated = a.reduce(:concat)
or
concatenated = a.reduce(:+)

Related

MATLAB Search Within a Cell Array of Cells

Setup:
I have a 21 x 3 cell array.
The first 2 columns are USUALLY strings or char arrays, but could be 1xn cells of strings or char arrays (if there are multiple alternate strings that mean the same thing in the context of my script). The 3rd element is a number.
I'm looking to return the index of any EXACT match of with a string or char array (but type doesn't have to match) contained in this cell array in column 1, and if column 1 doesn't match, then column 2.
I can use the following:
find(strcmp( 'example', celllist(:,1) ))
find(strcmp( 'example', celllist(:,2) ))
And these will match the corresponding indices with any strings / char arrays in the top level cell array. This won't, of course, match any strings that are inside of cells of strings inside the top level cell array.
Is there an elegant way to match those strings (that is, without using a for, while, or similar loop)? I want it to return the index of the main cell array (1 through 21) if the cells contains the match OR the cell within the cell contains an exact match in ANY of its cells.
The cellstr function is your friend, since it converts all of the following to a cell array of chars:
chars e.g. cellstr( 'abc' ) => {'abc'}
cells of chars e.g. cellstr( {'abc','def'} ) => {'abc','def'}
strings e.g. cellstr( "abc" ) => {'abc'}
string arrays e.g. cellstr( ["abc", "def"] ) => {'abc','def'}
Then you don't have to care about variable types, and can just do an ismember check on every element, which we can assume is a cell of chars.
We can set up a test:
testStr = 'example';
arr = { 'abc', 'def', {'example','ghi'}, "jkl", "example" };
% Expected output is [0,0,1,0,1]
Doing this with a loop to better understand the logic would look like this:
isMatch = false(1,numel(arr)); % initialise output
for ii = 1:numel(arr) % loop over main array
x = cellstr(arr{ii}); % convert to cellstr
isMatch(ii) = any( ismember( testStr, x ) ); % check if any sub-element is match
end
If you want to avoid loops* then you can do this one-liner instead using cellfun
isMatch = cellfun( #(x) any( ismember( testStr, cellstr(x) ) ), arr );
% >> isMatch = [0 0 1 0 1]
So for your case, you could run this on both columns and apply some simple logic to select the one you want
isMatchCol1 = cellfun( #(x) any( ismember( testStr, cellstr(x) ) ), arr(:,1) );
isMatchCol2 = cellfun( #(x) any( ismember( testStr, cellstr(x) ) ), arr(:,2) );
If you want the row index instead of a logical array, you can wrap the output with the find function, i.e. isMatchIdx = find(isMatch);.
*This only avoids loops visually, cellfun is basically a looping device in disguise, but it does save us initialising the output at least.

Is there any way to create dynamic array in scala? Means inserting values at run time?

var arr=Array.ofDim[Int](4,4)
arr(0)(0)(0)(0)=12
this is one way to insert elements in array.
but if i need to initialize size of array dynamically or at run time. How can we do it in scala?
Here
val n = StdIn.readInt
val m = StdIn.readInt
val arr = Array.ofDim[Int](n, m)
arr(5)(15) = 1
println(arr.deep.mkString("\n"))
I created 2-dimensional array with sizes known only in runtime (I entered 10 and 20).
Or maybe you need scala.collection.mutable.ArrayBuffer if you're going to change sizes.
ArrayBuffer[Int] is 1-dimensional, ArrayBuffer[ArrayBuffer[Int]] is 2-dimensional etc.
val arr: ArrayBuffer[ArrayBuffer[Int]] =
ArrayBuffer.fill(10)(ArrayBuffer.fill(20)(0))
arr(5)(15) = 1
println(arr.mkString("\n"))
println
arr(5) += 1
arr += ArrayBuffer.fill[Int](25)(0)
println(arr.mkString("\n"))

How to extract different values/elements of matrix or array without repeating?

I have a vector/ or it could be array :
A = [1,2,3,4,5,1,2,3,4,5,1,2,3]
I want to extract existing different values/elements from this vector without repeating:
1,2,3,4,5
B= [1,2,3,4,5]
How can I extract it ?
I would appreciate for any help please
Try this,
A = [1,2,3,4,5,1,2,3,4,5,1,2,3]
y = unique(A)
B = unique(A) returns the same values as in a but with no repetitions. The resulting vector is sorted in ascending order. A can be a cell array of strings.
B = unique(A,'stable') does the same as above, but without sorting.
B = unique(A,'rows') returns the unique rows ofA`.
[B,i,j] = unique(...) also returns index vectors i and j such that B = A(i) and A = B(j) (or B = A(i,:) and A = B(j,:)).
Reference: http://cens.ioc.ee/local/man/matlab/techdoc/ref/unique.html
Documentation: https://uk.mathworks.com/help/matlab/ref/unique.html
The answers below are correct but if the user does not want to sort the data, you can use unique with the parameter stable
A = [1,2,3,4,5,1,2,3,4,5,1,2,3]
B = unique(A,'stable')

iPython numpy - How to change value of an array slice with a map

I've got a 3-dim array [rows][cols][3] with values between 0 and X.
I need to manipulate a specific dimension in the array. So I've taken a slice of the part I want to manipulate
arr_slice = array[:,:,0]
now I can make some manipulations like arr_slice *= 3 and that will change the original array, as I intended.
However, I need to change values according to a map, which is an array with size X that maps the values of the slice (0-X) to new values. the map is called mapping
so I know mapping[arr_slice] will do what I want, but using it like this:
arr_slice = mapping[arr_slice]
will of course change only arr_slice and not the original array I have.
So, How can I perform this task to change the original array?
The array is actually an image, that I'm trying to manipulate it's Y values in YIQ format:
im_eq = np.copy(im_orig)
if (rgb):
im_eq = rgb2yiq(im_eq)
im = im_eq[:,:,0]
else:
im = im_eq
mapping = get_cumutative_histogram(im)
im = mapping[im.astype(int)] # the problematic line
You need to address the slice elements:
im[:] = mapping[im.astype(int)]
for example:
from pylab import *
a = rand(10)
sl = a[4:9]
print sl # ->: array([ 0.97278179, 0.7894741 , 0.38051133, 0.42684762, 0.82670638])
sl[:] = 1
print a #-> array([ 0.21125781, 0.4235981 , 0.81950229, 0.93937973, 1. , 1. , 1. , 1. , 1. , 0.39047808])

Choose elements from array randomly in matlab and store the remain element

I have array contain 1 column with 225 rows and I want to select 170 elements from these elements randomly and store it in another array also store the remain elements at another array, I used this code to choose randomly elements but I don't know how I can store the remain elements (55) at another array !
Code : my original array A
msize = numel(A);
firstpart = A(randperm(msize, 170))
secondpart = !!!!! ( remain elements ) % This is my question
Instead of throwing away the other elements, just get a permutation of all of them and then partition the array:
msize = numel(A);
allperm = A(randperm(msize));
firstpart = allperm(1:170);
secondpart = allperm(171:end);
You can use boolean indexing.
A = rand(255,1); % just generating an example matrix
indices = false(size(A));
indices(randsample(1:numel(A),170)) = true; % select what to keep
firstpart = A(indices);
secondpart = A(~indices);

Resources