Stop xlsread from trimming last empty cells
1 次查看(过去 30 天)
显示 更早的评论
Hello,
So I'm importing Vectors (lets say 4x1 one) from a excel file to matlab.
values = xlsread(file, sheet, 'O9:O12');
so, obv. I want the values of 4 cells saved into the vector values(x), but the excel files either have a value in the cells, or NaN. Xlsread stops reading after the last number, so when i have for example:
[ 1, 2, nan, nan ](in one column)
I will get length(values) = 2, and values = 1, 2. But it's very important that the length stays 4 and i get the values 1,2,0,0 (switching the NaN's to zeroes is no prob, already happening later on)
I tried to preallocate it with zeros, with:
values = zeros(4,1);
But it doesn't help, it simply gets overwritten and Matlab changes the size down to a 2x1 vector for example.
(Excel file is not to be published, sorry - but nothing important inside for this question)
So, how can I set the length of the vector values(X) by force? I tried length(values) = 4 but that did garbage...
thx
0 个评论
回答(1 个)
Rik
2018-3-26
You can always do it with the dirty hack below
values = xlsread(file, sheet, 'O9:O12');
if length(values)<4,values(4)=0;end
You can also do a pre-allocation style:
tmp_values = xlsread(file, sheet, 'O9:O12');
values=zeros(1,4);
values(1:numel(tmp_values))=tmp_values;
This will not return an error if you extend the Excel range and it reads more than 4 elements.
2 个评论
Rik
2018-3-26
What the first solution does is setting the 4th element to 0 if there are less than 4 elements. This means it will extend a vector to this length, but not overwrite the 4th position if there already is data there.
Both strategies have the length of 4 hard coded, so to use them with a 96 element vector, you should adapt them. To automatically do this, you could write a function that extracts the expected number of elements from the provided range, but that might be overkill.
If my answer helped you, please consider marking it as accepted answer.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!