How to get NaN when txt file is not exist

2 vues (au cours des 30 derniers jours)
BENJAMIN BUCHDA
BENJAMIN BUCHDA le 23 Fév 2021
Commenté : Walter Roberson le 18 Mar 2021
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 commentaires
Rik
Rik le 23 Fév 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 le 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

Connectez-vous pour commenter.

Réponses (1)

Shashank Gupta
Shashank Gupta le 25 Fév 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

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by