Extract one dimension from a multidimensional array [duplicate] - arrays

This question already has answers here:
On shape-agnostic slicing of ndarrays
(2 answers)
Closed 6 years ago.
Suppose A is multi-dimensional array (MDA) of size 3,4,5 and B is another MDA of size 3,4,5,6.
I know A(1,:,:) or B(1,:,:,:) can both extract their elements along the first dimension.
I now need to write a general program to extract the k-th dimension from a MDA without knowing its size.
For example, the MDA C has 6 dimension: 4,5,6,7,8,9 and I want an extraction C(:,:,k,:,:,:).
Sometimes, the MDA 'D' has 4 dimension: 3,4,5,6 and I want another extraction D(k,:,:,:).
That is, my problem is the numbers of colon is varying because of the dimension.
Thanks in advance

You can use string arrays to index the array dynamically:
function out = extract(arr,dim,k)
subses = repmat({':'}, [1 ndims(arr)]);
subses(dim) = num2cell(k);
out = arr(subses{:});
where dim is the dimension in which you want to select and k is an index within that dimension.
I have used a code from this answer:
https://stackoverflow.com/a/27975910/3399825

Related

Python numpy: Selecting array entries based on input array [duplicate]

This question already has answers here:
Getting the indices of several elements in a NumPy array at once
(5 answers)
Closed 2 years ago.
Assume I have an array:
a = np.array([1,2,3,4,5])
Now I want to find the indices of elements in this array corresponding to the values given by another array input:
input = np.array([2,4,5])
The expected result should be:
result = [1,3,4]
A boolean mask, which is true for element indices 1,3,4 would also be fine.
I do not want to use looping to solve this. I assume that a possible solution has to do with the numpy where() function, but using this one, I am only able to compare the entries of array a with one element of array input at a time. Because the length of input might differ, I cannot really use this approach. Do you have any other ideas?
Thanks in advance.
np.where(np.in1d(a, inp))[0]
or:
np.isin(a, inp).nonzero()[0]
or as suggested here:
sorter = np.argsort(a)
sorter[np.searchsorted(a, inp, sorter=sorter)]
output:
[1 3 4]
np.where(np.in1d(a, inp))[0] np.where(np.in1d(a, inp))[0]

Array size in NxN matrix - Swift [duplicate]

This question already has answers here:
Two-dimensional array in Swift
(11 answers)
Closed 3 years ago.
May I know how I can get the array size of NxN matrix
like number of rows and no: of columns where my input is 4x4
arr[4][4]
Is it something like arr[N].count for rows and arr[][N].count for columns?
Please advice
Using the built-in Array type, you cannot create a two-dimensional Array (which you refer to as matrix) that's guaranteed to be "NxN", because you cannot guarantee that all inner arrays will have the same number of elements and you also cannot guarantee that the number of elements in the inner arrays will be the same as the number of arrays in the two-dimensional array.
However, you can access the number of inner arrays (or "rows") using arr.count and you can access the number of elements in the inner arrays using arr[i].count (which will be the number of "columns" assuming that all inner arrays have the same number of elements).
If you'll be using two-dimensional Arrays a lot and you want to guarantee that all of the inner arrays have the same number of elements, I'd suggest creating a custom Collection.
You can use count or endIndex to get the dimensions but you need to check each row separately.
var matrix: [[Int]] = [[1,2,3], [4,5,6,7], [8,9]]
print(matrix.count)
for i in 0..<matrix.endIndex {
print(matrix[i].endIndex)
}

how to access an element of an n-D matrix where index comes from a mathematical operation [duplicate]

This question already has answers here:
MATLAB: Accessing an element of a multidimensional array with a list
(2 answers)
Use a vector as an index to a matrix
(3 answers)
Closed 5 years ago.
How can I access an element of an n-D matrix where index comes from a mathematical operation in Matlab?
For example I have a 4D Matrix called A.
I want to access element 1,1,1,1 which results from (3,4,5,6) - (2,3,4,5)
Is there any way I can do this assuming that the array can be any dimension d and that the array from subtraction will always be d elements long?
One possible way would be to utilise the fact that MATLAB can use linear indexing for any n-dimensional array as well as row-column type indexing. Then you just have to calculate the linear index of your operation result.
There may be a more elegant way to do this but if x is the array holding the result of your operation, then the following works
element = A(sum((x-1).*(size(A).^[0:length(size(A))-1]))+1);
The sub2ind function feels like it should help here, but doesn't seem to.
Another approach is to converting to a cell array, then to a comma-separated list:
A = rand(3,4,5,6); % example A
t = [2 1 3 4]; % example index
u = num2cell(t);
result = A(u{:});

F# - assigning element in (jagged) 2d-array sets several elements [duplicate]

This question already has an answer here:
Array.create and jagged array
(1 answer)
Closed 6 years ago.
I'm experiencing some behavior in f# that i do not understand. I was trying to create a 2d table using nested arrays. The sub-arrays will have the same length, so I could have used Array2D. However later on I will need the table rows as normal arrays, so in order to avoid conversion from a multidimensional to a regular array I want to represent the table as a jagged array.
The following code is an example of how I initialize and assign elements in the table.
let table = Array.create 3 (Array.zeroCreate<int> 2);;
table.[0].[0] <- 1;;
I would expect this piece of code to set the first element in the first row. However, what it actually does is setting the first element in all three rows.
table;;
val it : int [] [] = [|[|1; 0|]; [|1; 0|]; [|1; 0|]|]
Why does table.[0].[0] set the first element in all three sub-arrays? I tried finding the memory addresses of the sub-arrays using System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement, and it seems to me that they are different, so they three rows are not the same array. What is going on here?
When you use array.create, it takes as an argument an object, not a function.
As a result, each element of the jagged array is a reference to the same array, so you get the observed behaviour.
Just use a function other than array.create to make the array

Storing multiple powers of matrices in matlab [duplicate]

This question already has answers here:
How to generate the first twenty powers of x?
(4 answers)
Closed 7 years ago.
I have 1000 matrices with dimensions 2x2.
What I now need to do is to get 30 consecutive powers of those matrices (A^2, A^3... ...A^30) and store them all.
I found a topic that suggested using bsxfun:
Vectorizing the creation of a matrix of successive powers
However, bsxfun does not work with cell arrays ("Error using bsxfun
Operands must be numeric arrays").
What can I do?
PS. A secondary question: once I have them, I want to plot 4 graphs (each corresponding to 1 of the elements of the 2x2 matrices) with 30 positions (x-axis) which will show confidence bands (16th and 84th percentile).
EDIT: Someone linked to a question that was similar to the one that I linked. From what I can understand, the question there is about a vector, not array of matrices.
Assuming your array A is 2-by-2-by-1000, here are two loops to make things work:
A = rand(2,2,1000);
K = 30;
%%
N = size(A,3);
APower = zeros(2,2,N,K);
APower(:,:,:,1) = A;
for i = 1:N
for k = 2:K
APower(:,:,i,k) = A(:,:,i)*APower(:,:,i,k-1);
%// Alternatively you could use:
%APower(:,:,i,k) = A(:,:,i)^k;
end
end
You need to replicate the matrix 30 times to do this using cellfun. For example,
a = repmat(A{1},1,30);% Select one of your A matrices
b = num2cell(1:30);
x = cellfun(#(a,b) a^b,a,b,'UniformOutput',false)
Since you need to run cellfun for each element of A another way is to use arrayfun as below.
a = A{1};
b = 1:30;
x = arrayfun(#(b) a^b,b,'UniformOutput',false)

Resources