Error in hand written code
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
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'))
PrintStat(LoadData('L14UnivStatData01.txt'))
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
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?
참고 항목
카테고리
Help Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!