On Monday, February 22, 2016 at 12:18:02 PM UTC+2, Tamas Papp wrote:
>
>
> On Mon, Feb 22 2016, Aleksandr Mikheev wrote:
>
> > Hi everyone. I have two simple questions, answer to which I cannot find
> by
> > myself.
> >
> > 1. Is there any way to add an element to array? For example, I have
> > Array{...}(n,m) or Vector{...}(n). And I'd like to expand it, i.e. I
> want
> > to have now Array{n+1,m} or Vector{...}(n+1). How can I do this?
>
> See push! and resize! for vectors. For general arrays, I would just use
> hcat to make a new one if I am only doing this a few times, but you can
> find messages on the lists with tricks to avoid reallocation if
> performance is critical (grow them by more than a single row, eg
> doubling). Alternatively, you can use a vector of vectors and
> concatenate them when you have the result.
>
> > 2. Imagine I have an array [1 2 3 4 5 6 7 8 9 10; 12 4 5 0 2 0 45 8 0
> 7].
> > Is there any easy way to remove all columns with 0 in second line?
> > Something like filter!(...)?
>
> Try something like
>
> A[:,mapslices(col->all(col.!=0),A,1)]
>
> This could be slightly faster (not benchmarked):
>
> function columnswithzeros{T <: Number}(A::AbstractArray{T,2})
> n,m = size(A)
> z = zeros(Bool,m)
> for col = 1:m
> for row = 1:n
> if A[row,col] == 0
> z[col] = true
> break
> end
> end
> end
> z
> end
>
> A[:,~columnswithzeros(A)]
>
> Best,
>
> Tamas
>
For question #1: hcat(...) and cat(...) as Tamas suggested.
For question #2:
a = [1 2 3 4 5 6 7 8 9 10; 12 4 5 0 2 0 45 8 0 7]
a = a[:,a[2,:].!=0]
a
2x7 Array{Int64,2}:
1 2 3 5 7 8 10
12 4 5 2 45 8 7