How could we add elements in a new array? and how could we use "if" with mutiple conditions?

Hello all,

In matlab, we could use X = to define an empty array and then add elements in X like X[1] = 2 or X[i] = rand in a for loop and does not require us to know the size of X in advance.

I was wondering how could I do this in Julia? Here is my code,Coo is a 500-element Vector{Vector{Float64}}.

using Plots
using JLD
using StaticArrays
Coo = load("data.jld")["data"] 
x = load("data2.jld")["data"] 
y = load("data3.jld")["data"] 
gx = []
for i = 1:length(Coo)
    if Coo[i][1] >4  & Coo[i][2] <4
        gx[i] = Coo[i][1]

This line

Coo[i][1] >4  & Coo[i][2] <4

and this line here

gx[i] = Coo[i][1]

both failed and have problems. Sorry that I feel confused to debug them at this stage.
Could you please give some suggestions or comment on this?
Thank you in advance!

To answer half, you want && instead of &.

1 Like

For the other half of your question, you want push!

1 Like

To expand on this answer:

help?> &                                    
search: & &&                                
  x & y                                     
  Bitwise and. Implements three-valued logic [...]

help?> &&                                                                      
search: &&                                                                     
  x && y                                                                       
  Short-circuiting boolean AND.                                                
  See also &, the ternary operator ? :, and the manual section on control flow.

If you enter ? in the REPL and enter a symbol, function name, operator etc., you’ll get this sort of documentation. Most packages and almost everything in julia Base has this sort of documentation available.

In general, I’d recommend checking out the manual (especially the section about differences from Matlab) if you’re new to the language.


Thank you very much all !
It is really helpful and now I know how to seek helps from Julia documentation!

Note that this is an anti-pattern in Julia, because it creates an array of elements of Any type:

julia> x = []

this is very bad for performance. You should always (when possible) specify the type of data that the vector will contain:

julia> x = Float64[]

By the way, another anti-pattern in Julia is to heavy computations outside functions. In that particular example, you should do

function update!(gx,Coo)
  for i = 1:length(Coo)
      if Coo[i][1] >4  & Coo[i][2] <4
          gx[i] = Coo[i][1]

and call this with update!(gx,Coo).


Amazing! Really appreciate these helps!