Remove specific rows of matrix from memory not just delete them
2 次查看(过去 30 天)
显示 更早的评论
I'm writting an excel using Matlab. The problem is that when I'm trying to remove certain rows I get the result shown in the jpg. I don't want the empty rows.
for c = 1:1000
u=H(c,1)
if (u~=0)
Hf(c,1)=H(c,1);
else
Hf=NaN;
end
end
0 个评论
采纳的回答
Image Analyst
2023-5-5
Try this instead of all that code you have:
rowsToTransfer = (H(:, 1) ~= 0);
Hf = H(rowsToTransfer, :);
If you just want the first thousand rows, you can do this:
rowsToTransfer = (H(1 : 1000, 1) ~= 0);
Hf = H(rowsToTransfer, :);
0 个评论
更多回答(1 个)
dpb
2023-5-5
Hf=Hf(HF~=0);
for the case you show that Hf is a vector. If it were an array but to remove the rows based on the one column is almost as easy--
Hf=Hf(HF(:,1)~=0,:);
The above is easier for the novice to see if write
ix=(HF(:,1)~=0); % the logical T/F vector of column 1 not zero
Hf=Hf(ix,:); % keep those rows, all columns
5 个评论
dpb
2023-5-5
"...H is one matrix, and Hf is a second, output matrix...."
Yes, that's what OP wrote,but given his problem description there's no need to not do the operation in place, I didn't see any reason to not write the optimal solution of not duplicating data needlessly. Of course, it is always possible may want/need to keep the original as well; in that case then, indeed, would need to have another LHS variable or another solution.
dpb
2023-5-5
It's more inefficient to write multiple times to the same workbook/worksheet if can avoid it, but if it can't be helped, then use the optional 'Range' named parameter to set the location in the worksheet at which to write the additional data that doesn't overwrite the first. These are all illustrated in the documentation.(*)
Unless you are using a truly by now ancient version of MATLAB, xlsread and xlswrite have been deprecated for ages; use writematrix and friends, instead. They are much improved in both features and speed.
(*) The best way in a case such as this would be to create the data as either a 2D array and augment the shorter column with NaN to the length of the longer; then writematrix() the array. Or, create a cell array that is 2x1 with each cell containing the given column as a vector of doubles. Then use writecell instead.
另请参阅
类别
在 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!