How to get NaN when txt file is not exist

2 views (last 30 days)
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 Comments
Rik
Rik on 23 Feb 2021
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 on 18 Mar 2021
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

Sign in to comment.

Answers (1)

Shashank Gupta
Shashank Gupta on 25 Feb 2021
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

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!