In matlab Write a function ret=excel_columnaverage(filename,column) that takes a
ID: 3845962 • Letter: I
Question
In matlab
Write a function ret=excel_columnaverage(filename,column) that takes an Excel file's name, and a column id (or name) and returns the average of the numbers in that column. If column is a number, it directly denotes the column number. If column is a string, you need to find a case-insensitive match in the first header row to determine the column number. When taking the average of the values in a column, any entry not containing a number should be ignored.
Hints: Matlab's xlsread() function returns three output arguments: num,txt,raw. It is best to use raw output to solve this problem. If the input column variable is a string, use the first row of raw to find the column number. Once you identify the column number, extract the requested column into a vector rawvector. Write a for loop that goes over each element of the rawvector and collects the entries containing a valid number into a vector v . Only consider entries that contain a number (isnumeric()), and are not NaN (isnan()). After the loop, you can calculate the average of the numbers accumulated in v .
Example:
>> disp(xls_columnaverage('crps_data.xlsx',2))
44.8197
>> disp(xls_columnaverage('crps_data.xlsx','bmi'))
27.2189
Explanation / Answer
function ret=excel_columnaverage(filename,column)
[~,~,raw] = xlsread(filename);
Size=size(raw);
if ischar(column)
l=1;
length(column)
for j=1:length(column)
if j==1
column2(l)=upper(column(j));
l=l+1;
else
column2(l)=column(j);
l=l+1;
end
end
if ischar(column)
for i=1:Size(2)
if strcmp(raw(1,i),column)||strcmp(raw(1,i),column2)
columnNumber=i;
end
end
end
end
if isnumeric(column)
columnNumber=column;
end
rawvector=cell2mat(raw(2:end,columnNumber))';
k=1;
for i=1:numel(rawvector)
if(isnumeric(rawvector(i))==1&&isnan(rawvector(i))==0)
v(k)=rawvector(i);
k=k+1;
end
end
ret=mean(v);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.