- Hard to say, since you don't show what's in the cells of data_cell
- Why use a cell array in the first place?
Storing data in nested for loop
3 ビュー (過去 30 日間)
古いコメントを表示
Dear all,
I have a cell let say :
cell_data= cell([400, 4)])
when I loop to perform some calculations: I go the the error "Subscripted assignment dimension mismatch."
I am doing the following:
for s=1:1:3
for k=1:1:4
for n=1:1:300;
zero_index=find(cell_data{s}(n, : , k)~=0); %%to find the index of values which are not zeros
nonZero_data=cell_data{s}(n, zero_index, k);
new_cell_data{s}(n,:, k)=nonZero_data
end
end
end
I got the error. Do you know why. Thanks...
2 件のコメント
per isakson
2017 年 10 月 30 日
回答 (1 件)
Guillaume
2017 年 10 月 30 日
This has nothing to do with the cell array.
Within each cell of your cell array, you have a 3D matrix. You are looping over the rows and pages of that 3D matrix and finding the non-zero elements in each column (by the way you don't need the ~=0, that's what find returns anyway). You are then putting the non-zero elements of the column into a new matrix. The problem is that for each column, you're not going to have the same numbers of non-zero elements in each columns. Hence you can't store them in a matrix.
You could potentially store them in cell arrays within your main cell array. But I suspect that a completely different approach would be better. What is the end goal?
4 件のコメント
Guillaume
2017 年 10 月 31 日
As I said you cannot construct a matrix that have rows of different size which is what will happen if you remove the 0s. What you can do is replace the 0s by NaNs and tell mean to ignore these NaNs.
Note that your k and n loops are completely unnecessary and only slow down your code. Learn to operate on whole matrices at once. In addition, since the matrices stored in your cell array have all the same size, you could just store them as a single higher dimension matrix which means you would need no loop at all.
Keeping it in a cell array (if matrices can be different size)
cell_average = cell(size(cell_data));
for cidx = 1:numel(cell_data))
cell_data_matrix = cell_data{cidx};
cell_data_matrix(cell_data_matrix == 0) = nan; %replace 0 by nan
cell_average = mean(cell_data_matrix, 2, 'omitnan'); %get mean across columns
end
Average = permute(cat(4, cell_average{:}), [4, 1, 3, 2]); %permute to get your s,n,k order
Storing it all in a higher dimension matrix:
data_matrix = cat(4, cell_data{:}); %store in higher dimension matrix;
data_matrix(data_matrix == 0) = nan; %replace 0 with nan
Average = permute(mean(data_matrix, 2, 'omitnan'), [4, 1, 3, 2]); %calculate mean and rearrange dimensions
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!