Azzera filtri
Azzera filtri

Creating a cell array within a nested loop

3 visualizzazioni (ultimi 30 giorni)
KCE il 5 Ott 2022
Commentato: Jiri Hajek il 10 Ott 2022
I am trying to fill cell arrays with values within a loop, but I am not entirely sure how to do this for what I need.
'zdr_bin' and 'ht_bin' below are subsets of bigger arrays, and each of these *_bin variables can sometimes be 0, or sometimes 30-50 entries, etc, depending on the radar scan (these loops are nested within a larger loop). Ultimately, I need these entries at each i,j pair in a 3D variable. Since it can vary in the 3rd dimension (which is all values in zdr_bin or ht_bin), I was thinking a cell array makes sense. I am not sure how to index this because this last part fails, any thoughts are appreciated!
Attached below is the small loop where my code is failing.
%loop through all model grid points to create bins around each model grid point
for i=1:2:size(lon,1)
for j=1:2:size(lon,2)
%calculate distance of all observations from model grid point
mod_dist = deg2km(distance(lat(i,j),lon(i,j),obs_lat,obs_lon));
%take observations within the distance threshold, and therefore in the bin
bin_ind = find(mod_dist<dist_thres);
%add bin values to a variable
zdr_bin=zdr(bin_ind); ht_bin=obs_h(bin_ind);
%if variable is not filled, go to next iteration
if length(zdr_bin)<1; continue; end;
%add to a cell array
zdr2{:}(i,j)=zdr(bin_ind); ht2{:}(i,j)=obs_h(bin_ind);

Risposte (1)

Jiri Hajek
Jiri Hajek il 5 Ott 2022
You did not mention the error message you get, but the line where you are trying to add new entry into cell array contains an incorrect indexing. Namely, zdr2{:} produces a comma-separated list of all values in the cell array, so it is not possible to subsequently index into it with (i,j). You have to put the cell indices into curly braces like this: zdr2{i,j} and directly access the appropriate cell, when storing a single cell value. Note also that zdr2(i,j) is a cell, whereas zdr2{i,j} is the contents o fthe cell...
  4 Commenti
KCE il 7 Ott 2022
I still get the same error with the second option. I cannot really preallocate the array because I will not know how big it will be until 'bin_ind' is found in each iteration k.
Jiri Hajek
Jiri Hajek il 10 Ott 2022
By "second option" you mean a 3D array? I understand that you may be unable to preallocate the third dimension in this case, but that is not really a problem in MATLAB, it would only cause some slow-down.

Accedi per commentare.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by