Removing zeros in excel

3 次查看(过去 30 天)
Hi Guys,
Does anyone know how to remove zeros while keeping the zero that is at the beginning and end of a value from excel sheet to make figure 1 to look like figure 2.
Thank you!
  6 个评论
Walter Roberson
Walter Roberson 2019-2-7
II am not clear on why the 0 is not preserved on top of the column with 4s?
Bob Thompson
Bob Thompson 2019-2-7
编辑:Bob Thompson 2019-2-7
There are two 0s on top of the 4s, only the adjacent one is retained.
At least that is what it looks like to me.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2019-2-7
No loop, no cellfun:
filetoedit = 'C:\somewhere\somefile.xlsx';
[data, ~, ascell] = xlsread(filetoedit);
ascell(~conv2(data ~= 0, [1; 1; 1], 'same')) = {[]}; %the conv2(data ~= 0, [1; 1; 1], 'same') expands non-zeros one row up and down. The remaining 0 are replaced by []
xlswrite(filetoedit, ascell);

更多回答(1 个)

Bob Thompson
Bob Thompson 2019-2-7
Guillaume and Walter will probably have much better methods for doing this, but here is my first thought.
[num,txt,data] = xlsread('myfile.xlsx'); % Read the excel file
for i = 1:size(data,1); % Loop through rows
for j = 1:size(data,2); % Loop through columns
if i > 1 & i < size(data,1) & data{i,j} == 0 & data{i+1,j} == 0 & data{i-1,j} == 0
data{i,j} = [];
elseif i == 1 & data{i,j} == 0 & data{i+1,j} == 0
data{i,j} = [];
elseif i == size(data,1) & data{i,j} == 0 & data{i-1,j} == 0
data{i,j} = [];
end
end
end
Unfortunately, I wasn't able to find a method that didn't involve loops, but I'm also not very good with cellfun.
  1 个评论
Guillaume
Guillaume 2019-2-7
cellfun is just a loop in disguise, often slower. What you gain with cellfun is guarantee that the output is the correct size and clarity (in my opinion) of the code. cellfun is also an example of functional programming which may be preferred over the imperative nature of loops.
Neither loops, nor cellfun are needed for this however.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Import from MATLAB 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by