fill a matrix within a loop
42 次查看(过去 30 天)
显示 更早的评论
Hello everyone,
I am growing more confident in Matlab, thanks to community support, but sometimes I feel stucked due to very silly issues, as per the following case:
matr_counts_per_chunk = zeros(120,2752);
for col= 1:length(tr_x_ch)
matr_mat_fil_non_bool_sigle_tr = resh_matr_mat_fil_non_bool(:,col);
matr_counts_per_chunk(:,col) = sum(reshape(matr_mat_fil_non_bool_sigle_tr,[],250),2);
end
the problem is: matr_counts_per_chunk is only correctly filled in the first iteration, then I get only zeros in every 2751 left columns. This mean the for loop is actiually doing nothing/not working except for the first call.
Any help will be appreciated
7 个评论
Stephen23
2023-4-29
"In the attachemnts you will find the actual matrix in order to run the code yourself. "
Nope: you did not include tr_x_ch as Image Analyst requested, nor have you described its size as I requested.
采纳的回答
更多回答(1 个)
Image Analyst
2023-4-29
Here's what I get, after adding comments and clarifying the variable names.:
fileName = 'resh_matr_mat_fil_non_bool.mat';
load(fileName) % Load "resh_matr_mat_fil_non_bool" from a .mat file.
% resh_matr_mat_fil_non_bool is a 30,000 row by 2752 column 2-D matrix.
[rows, columns] = size(resh_matr_mat_fil_non_bool)
tr_x_ch = zeros(rows, 1); % A 2752 column vector.
% Preallocate a matrix.
matr_counts_per_chunk = zeros(120, 2752);
for col = 1 : columns
% Get data into a 30,000 by 1 column vector.
thisColumn = resh_matr_mat_fil_non_bool(:, col);
% Reshape into 120 rows by 250 columns.
matrix2d = reshape(thisColumn, [], 250);
% Sum the matrix across, getting a 250 row by 1 column vector
% and put the sums into the column of matr_counts_per_chunk;
matr_counts_per_chunk(:, col) = sum(matrix2d, 2);
end
fprintf('Done!\n')
matr_counts_per_chunk has values all over the matrix, not just in the first column, so I can't reproduce what you said. It basically does what you tell it to.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!