Error in hand written code

2 ビュー (過去 30 日間)
SWARNENDU PAL
SWARNENDU PAL 2020 年 12 月 9 日
コメント済み: Rik 2020 年 12 月 10 日
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.

回答 (1 件)

Rik
Rik 2020 年 12 月 9 日
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.
PrintStat(LoadData('c.mat'))
mean: 25.84
PrintStat(LoadData('L14UnivStatData01.txt'))
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))
end
function data=LoadData(filename)
%[write help text here]
data = load(filename);
if isa(data,'struct')
fn=fieldnames(data);
if numel(fn)>1
warning('file contains multiple variables, selecting first one')
end
data=data.(fn{1});
end
end
  2 件のコメント
Rik
Rik 2020 年 12 月 10 日
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?

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by