Stop xlsread from trimming last empty cells
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Rik
am 26 Mär. 2018
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 Kommentare
Rik
am 26 Mär. 2018
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.
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!