MATLAB Answers


Import from Excel and exclude fully blank rows

Francesco Ardia さんによって質問されました 2017 年 12 月 12 日
最新アクティビティ Michal Dobai さんによって 回答されました 2017 年 12 月 13 日
Hi everyone! I'm trying to modify a code generated by the import tool, thus making the code more flexible with respect to changes in the original Excel file.
The autogenerated code states:
raw(cellfun(@(x) ~isempty(x) && isnumeric(x) && isnan(x),raw)) = {''};
% Find row with blank cells
I = any(cellfun(@(x) isempty(x) || (ischar(x) && all(x==' ')),raw),2);
raw(I,:) = [];
This excludes rows with even a single blank cell. I want to import the whole Excel sheet and then exclude fully blank rows, how can I achieve this?

  3 件のコメント

Michal Dobai 2017 年 12 月 13 日
Just change
I = any(cellfun(@(x)...
I = all(cellfun(@(x)...
Francesco Ardia 2017 年 12 月 13 日
Thanks a lot, it works!
Michal Dobai 2017 年 12 月 13 日
Glad I could help. :)
I will post it as an answer, then.

サインイン to comment.

1 件の回答

回答者: Michal Dobai 2017 年 12 月 13 日

Just change this:
I = any(cellfun(@(x)...
to this:
I = all(cellfun(@(x)...
Why? Let' have a closer look at your code. On this line:
I = all(cellfun(@(x) isempty(x) || (ischar(x) && all(x==' ')),raw),2);
cellfun() returns logical array same size as raw. At position of every empty cell or cell containing only spaces will be 1. Rest of elements will be 0.
Now we want to find fully blank rows. That means, in our logical array we have to find 'all ones' rows. And that's exactly what all() does. Second argument, number 2, is dimension to operate along. In our case, it says we want to get a column vector which tells us for each row if it is empty or not.
B = all(A,dim) Determine if all array elements are nonzero or true. Tests elements along dimension dim. The dim input is a positive integer scalar.
Function any() works same way, but instead of determine if all array elements are nonzero or true it says if any of them are. (if there is at least one such element).
And finally, when we have column vector I - position of lines that are empty, we can delete them.
raw(I,:) = [];

  0 件のコメント

サインイン to comment.

Translated by