sub

..  sub(A, inds...)

Like :func:`getindex`, but returns a view into the parent array ``A`` with the given indices instead of making a copy.  Calling :func:`getindex` or :func:`setindex!` on the returned :obj:`SubArray` computes the indices to the parent array on the fly without checking bounds.

Examples

The sub function in Julia generates a view into the parent array A with the given indices, instead of creating a copy. It behaves similarly to the getindex function. Calling getindex or setindex! on the returned SubArray computes the indices to the parent array on the fly without checking bounds.

Here are some examples of how the sub function can be used:

  1. Create a subarray from a vector:

    julia> A = [1, 2, 3, 4, 5];
    julia> sub(A, 2:4)
    3-element SubArray{Int64,1,Array{Int64,1},Tuple{UnitRange{Int64}},true}:
    2
    3
    4

    This example creates a subarray that includes elements at indices 2, 3, and 4 from the vector A.

  2. Generate a subarray from a matrix:

    julia> B = [1 2 3; 4 5 6; 7 8 9];
    julia> sub(B, 1:2, 2:3)
    2×2 SubArray{Int64,2,Array{Int64,2},Tuple{UnitRange{Int64},UnitRange{Int64}},true}:
    2  3
    5  6

    In this example, a subarray is created from the original 3x3 matrix B by selecting rows 1 and 2, and columns 2 and 3.

  3. Modify the parent array using subarray indices:
    julia> C = [10, 20, 30, 40, 50];
    julia> sub(C, 2:4) .= [15, 25, 35];
    julia> C
    5-element Array{Int64,1}:
    10
    15
    25
    35
    50

    This example demonstrates how modifying the subarray using setindex! affects the original array C.

It's important to note that when using sub, the returned SubArray does not perform bounds checking. Therefore, it is the responsibility of the user to ensure that the provided indices are valid for the parent array.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: