Slicing an Array - arrays

I am having trouble finding a matlab function to slice an element out of an array.
For example:
A = [1, 2, 3, 4]
I want to take out on element of this array, say the element 3:
B = [1, 2, 4]
Is there a matlab function for this or would I have to code the algorithm to construct a new array with all the elements of A except 3?

Do this:
index_of_element_to_remove = 3;
A(index_of_element_to_remove) = [];
now A will be [1 2 4]
If you want to remove more elements at the same time you can do:
index_of_element_to_remove = [1 3];
A(index_of_element_to_remove) = [];
now A will be [2 4]

By value, which will remove all elements equal to 3
A(find(A==3)) = []
Or by index
A(3) = []

Related

Repetition of array elements in MATLAB

I have a MATLAB array and want to make a repetition based on the number of array elements. Below is the example that I want.
a = [2, 4, 6, 8]
If I want 7 elements, the result is
aa = [2, 4, 6, 8, 2, 4, 6]
Or if I want 5 elements,
aa = [2, 4, 6, 8, 2]
Is there any MATLAB function which makes these kind of result?
You can use "modular indexing":
a = [2, 4, 6, 8]; % data vector
n = 7; % desired number of elements
aa = a(mod(0:n-1, numel(a))+1);
One simple option will be to use a temporary variable for that:
a = [2 4 6 8];
k = 7;
tmp = repmat(a,1,ceil(k/numel(a)));
aa = tmp(1:k)
First, you repeat the vector using the smallest integer that makes the result larger than k, and then you remove the excess elements.
If you do that many times you can write a small helper function to do that:
function out = semi_repmat(arr,k)
tmp = repmat(arr,1,ceil(k/numel(arr)));
out = tmp(1:k);
end

Slice array of arbitrary dimension with lists of start and end indices

I need to copy a part of a 3D array.
I have the indexes of start and end of the copy.
For example 2D array:
[[2 2 3 4 5]
[2 3 3 4 5]
[2 3 4 4 5]
[2 3 4 5 5]
[2 3 4 5 6]]
starting index, end index are:
mini = [2, 1]
maxi = [4, 3]
So the result should be:
[[3 4 4]
[3 4 5]]
I can write:
result = matrix[mini[0]:maxi[0], mini[1]:maxi[1]]
Is there a way to do it generally ? for 3Dim or NDim arrays ?
The trick here is realizing what the indexing syntax is under the hood. This:
result = matrix[mini[0]:maxi[0], mini[1]:maxi[1]]
Is shorthand in python (not just numpy) for:
indices = slice(mini[0], maxi[0]), slice(mini[1], maxi[1])
result = matrix[indices]
So we just need to generate indices dynamically:
lower = [2, 1, ...]
upper = [4, 3, ...]
indices = tuple(np.s_[l:u] for l, u in zip(lower, upper))
result = matrix_nd[indices]
np.s_[a:b] is a shorthand for slice(a, b). Here we build a tuple containing as many slices as you have values in lower and upper
What you are looking for is the slice object, see that example:
matrix = np.random.rand(4,5)
mini = [2, 1]
maxi = [4, 3]
slices=[slice(b,e) for b, e in zip(mini,maxi)]
print(slices)
print(matrix[slices])
print(matrix[mini[0]:maxi[0], mini[1]:maxi[1]])

How to add values of arrays having different lengths [duplicate]

This question already has answers here:
Sum of arrays of different size [closed]
(4 answers)
Closed 6 years ago.
I want to add values of two different length array.
a =[1,2,3]
b= [1,2]
c = [1,2,3,4]
and so on..
I want result to be like [3,6,6,4]. How to do this in ruby on rails.
In order to make it dynamic, I would create arrays of array with your a, b, c =>
a = [1, 2, 3]
b = [1, 2]
c = [1, 2, 3, 4]
arrays = [a, b, c]
Then I would retrieve the max size :
max_size = arrays.map(&:size).max #=> 4
Then the following line would give you your answer :
max_size.times.map{ |i| arrays.reduce(0){|s, a| s + a.fetch(i, 0)}} #=> [3, 6, 6, 4]
You can build a new array that consists of all those array, and then can write the following code to get the array that has combined entries of each array:
a = [1,2,3]
b = [1,2,3]
c = [1,2,3,4]
Before you apply the rest of the code, you need to make sure that each array has the same length. For that, you can append 0 in all the arrays if need be, to ensure that each array has the same length as the rest of the arrays have.
a = [1,2,3,0]
b = [1,2,3,0]
c = [1,2,3,4]
combined_array = [a,b,c]
result = combined_array.transpose.map { |a| a.reduce :+ }
Extending the answer from #Arslan Ali
I added a way to make all the arrays the same size, so that his method of summing can be applied:
a = [1,2,3]
b = [1,2,3]
c = [1,2,3,4]
arrays = [a, b, c]
size = [a, b, c].map{|a| a.size}.max # Compute maximum size
combined_array = [a,b,c].map{|a| a.fill(a.size...size){0}} # Fill arrays to maximum size
result = combined_array.transpose.map { |a| a.reduce :+ } # Sum everything
Here's one way:
a = [1, 2, 3]
b = [1, 2, 3]
c = [1, 2, 3, 4]
[a,b,c].inject([]) do |totals, add|
add.each_with_index do |n, i|
totals[i] = (totals[i] || 0) + n
end
totals
end

MATLAB - A Cell Array's Most Repeated Element

I have a cell array containing 5 1x2 arrays. Is there any way to find the most repeated element? I think I cannot use the "mode" function. I looked it up on the internet and could not find a solution about the problem. Everybody keeps talking about cells array with strings.
The cell array I'm using is like this:
{[1 2], [2 5], [3 4], [1 2], [0 4]}
I would like MATLAB to find [1 2] as the most repeated element.
Thank you in advance.
For uniformly structured cell array (2 elements per cell) case
%// Convert the uniformly structured data to a 2D numeric array
Anum = vertcat(A{:})
%// ID unique rows and ID all rows based on those
[~,unqID,ID ] = unique(Anum,'rows')
%// Use 'mode' on ID and then index into unqID to get the index of
%// the most frequently occurring cell and finally index into the
%// input cell array with that index to get the desired output
out = A{unqID(mode(ID))}
Thus, for the given input data -
A = {[1 2], [2 5], [3 4], [1 2], [0 4]}
You would have -
out =
1 2
More generic case with cells of row vectors
If you are dealing with a cell array that has arbitrary sized row vectors in each cell, you can use this technique -
%// Get all elements of A
A_ele = [A{:}]
%// Get lengths of each cell
lens = cellfun('length',A)
%// Setup a 2D numeric array corresponding to the input cell array
A_num = zeros(max(lens),numel(lens))+max(A_ele)+1
A_num(bsxfun(#ge,lens,[1:max(lens)]')) = A_ele %//'
%// ID each row, find the mode with those & finally have the desired output
[unqrows,unqID,ID ] = unique(A_num.','rows') %//'
out = A{unqID(mode(ID))}
Thus, if you have input as -
A = {[1 2], [2 5], [3 4], [1 2], [0 4], [1 2 1],[9],[7 2 6 3]}
The output would still be -
out =
1 2
This works for a general cell array A:
A = {[4 2] [2 5] [4 2] [1 2 1] [9] [7 2 6 3] [1 2 1] [1 2 1] [7 9]}; %// example data
[ii, jj] = ndgrid(1:numel(A)); %// ii, jj describe all pairs of elements from A
comp = cellfun(#isequal, A(ii), A(jj)); %// test each pair for equality
[~, ind] = max(sum(comp,1)); %// get index of (first) most repeated element
result = A{ii(ind)}; %// index into A to get result

how to simplify array enumerations in swift

so I have an array and I want to add 1 to all the items.
var arr = [2, 3, 6, 9]
for (index, x) in enumerate(arr) {
arr[index] = arr[index] + 1
}
is there a simpler version of this? there's no reason to have 'x' in there. I know there's the alternate way of writing it this way:
arr[index] = x + 1
but that doesn't seem like enough reason to have 'x' there.
You can iterate indices of the array
var arr = [2, 3, 6, 9]
for index in indices(arr) {
arr[index] += 1
}
Essentially, indices(arr) is the same as arr.startIndex ..< arr.endIndex, but it's simple :)
OR, in this specific case, you might want to:
arr = arr.map { $0 + 1 }
Yes, this is a really good use case for the .map function.
var arr = [2, 3, 4]
arr = arr.map({$0 + 1})
// arr would now be [3, 4, 5]

Resources