Remove specific rows of matrix from memory not just delete them

4 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Image Analyst
Image Analyst il 5 Mag 2023
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, :);

Più risposte (1)

dpb
dpb il 5 Mag 2023
Use MATLAB <logical addressing> and vectorized operations--
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 Commenti
dpb
dpb il 5 Mag 2023
"...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
dpb il 5 Mag 2023
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.

Accedi per commentare.

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by