How to get NaN when txt file is not exist

2 次查看(过去 30 天)
This is a working function that gets the min, average, max of numbers with a specific row thershold however if i wanted to get an 'NaN' if the txt file or specfic column does not exist, how would I do that?
function res = columnStatistics(fPath, cat, cName)
fConn = fopen(fPath, 'r');
firstLine = fgetl(fConn);
new = [];
while ~feof(fConn)
cLine = fgetl(fConn);
Y = strsplit(firstLine, ',');
X = ismember(Y, cName);
V = find(X);
parts = strsplit(cLine, ',');
O = str2double(parts(V));
tru = strcmp(cat, parts{1});
if (tru)
new(end+1) = O;
else
res = [NaN];
end
end
fclose(fConn);
minData = min(new);
aveData = mean(new);
maxData = max(new);
final = [minData, aveData, maxData];
res = final;
end
  2 个评论
Rik
Rik 2021-2-23
I would encourage you to split the reading of the file and the processing you do with it. That way you can replace code when you need to.
If you want want to set the value NaN if the file doesn't exist, why don't you do that?
And why do you have so many empty lines? And no comments?
Walter Roberson
Walter Roberson 2021-3-18
You posted a question about labeling bars in alphabetic order, but deleted the question before my response made it up.
I post it here as the answer is not obvious.
====
Generalizing it to alphabetic when there was more than 26 possibilities was a bit tricky.
You should consider using categorical data for your x axis.
yData = (randi(9, 1, 30));
W = max(yData);
U = W + 5;
myFig = gcf;
myAx = axes(myFig);
myPlot = bar(myAx, yData);
myPlot.FaceColor = 'flat';
myAx.XTick = 1:length(yData);
myAx.YLim = [0 U];
myAx.Title.String = 'Data Visualization';
myAx.YLabel.String = 'Value';
myAx.XLabel.String = 'Category';
for i = 1:length(yData)
temp = dec2base(i-1,26);
temp(1:end-1) = temp(1:end-1) - 1;
myLab = blanks(length(temp));
mask = temp <= '9';
myLab(mask) = char(temp(mask) - '0' + 'A');
myLab(~mask) = char(temp(~mask) + 10);
myAx.XAxis.TickLabels{i} = myLab;
end

请先登录,再进行评论。

回答(1 个)

Shashank Gupta
Shashank Gupta 2021-2-25
Hey Benjamin,
Check out textscan function, it is useful in the same scenerio as you are interested in. This will help you fill up empty places in the data.
I hope this helps.
Cheers

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by