Creating a cell array within a nested loop
3 次查看(过去 30 天)
显示 更早的评论
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
%tic
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);
end
end
0 个评论
回答(1 个)
Jiri Hajek
2022-10-5
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 个评论
Jiri Hajek
2022-10-10
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!