Error in hand written code

1 view (last 30 days)
SWARNENDU PAL on 9 Dec 2020
Commented: Rik on 10 Dec 2020
I have attached a hand written function, which gives various informatio related to a univariate dataset. Now i have checked that my code is working for the .txt files only, even it does no works for .mat files. It shows error like :
Error using min
Invalid data type. First argument must be numeric or logical.
Error in PrintStat (line 9)
c{1,2} = min(data);
So i want to generalise the function for all type of unnivariate data. I have attached the function and one txt file and a mat file. Please check and guide me in doing this.Thank you.

Answers (1)

Rik on 9 Dec 2020
I personally prefer not to use load for text files, as it isn't obvious from the context that the specific text file will actually work. The load function will read some text files, in which case it will output an array. If you put in a mat file, it will return a struct.
What you should have done is de-couple the reading of your data and the processing. Your current function is doing two tasks. This means you can't recycle either part when you need to solve a similar problem.
mean: 25.84
mean: 12.34
function PrintStat(data)
% Statistical quantities measurement
% With the help of this hand written function one can find out the
% properties of the given dataset.
fprintf('mean: %.2f\n',mean(data))
function data=LoadData(filename)
%[write help text here]
data = load(filename);
if isa(data,'struct')
if numel(fn)>1
warning('file contains multiple variables, selecting first one')
SWARNENDU PAL on 10 Dec 2020
Thanks for your answer and support sir. But sir i dont want to use that loaddata function again. And one more thing can you explain what was wrong with my code!! It is working on text files but nnot on mat files. So if u could explain the mistake that will be very helpful sir. Thank you once again.
Rik on 10 Dec 2020
Why not? It is always better to make sure your functions do one Thing. You want two Things: load data from a file, and print a statistical analysis to the screen. Why do you insist on keeping it in one function? This way you can much more easily find where you used code previously, instead of trying to remember where you wrote code that is able to load txt and mat files.
As far as what was wrong with your code: look at my edits.
%This line was removed from PrintStat:
data = load(filename);
Look at what happened with that function instead. What did I add? Did you understand what I wrote in my answer in the first lines? You have two different kinds of files: mat files and text files. How does my code handle each?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!