nik-OS
nik-OS

Reputation: 327

MATLAB: Zeros appearing when storing values from different arrays to another array

I have two double arrays like the ones below:

K>> var_conx

var_conx =
     1
     3
   127
   129
   216
   217
   252
   253
   302
   303
   342
   343

and

K>> var_cony

var_cony =
     2
   126
   128
   216
   217
   252
   253
   302
   303
   342
   343

My task is pretty simple, I only need to store in an another double array all the common values of the two arrays, let's call the other array "common_convar". To be specific, for the two arrays above, i only want to store the values 216,217,252,253,302,303,342,343. For the other values, i do not care and i do not want them stored or whatever.

I have written the following code:

for i=1:length(var_conx)
    for j=1:length(var_cony)
        if var_conx(i)==var_cony(j)
           common_convar(i,:)=[var_conx(i)]; 
        end
    end
end

The problem i encountered here is that the array common_convar also stores some zeros in the beginning:

K>> common_convar

common_convar =

     0
     0
     0
     0
   216
   217
   252
   253
   302
   303
   342
   343

How is it possible to get rid of zeros and only store the desired common values of the two arrays var_conx and var_cony?

Thanks in advance for your time.

Upvotes: 0

Views: 61

Answers (1)

paisanco
paisanco

Reputation: 4154

Firstly you could find the elements common to both arrays, without having to do nested loops, using the Matlab set intersect function:

common_values= intersect(var_conx,var_cony);

Then you could find the nonzero elements of the common array via logical indexing:

common_values = common_values(common_values > 0);

Upvotes: 2

Related Questions