What changes is required ?

4 views (last 30 days)
Manav Divekar
Manav Divekar on 30 Nov 2021
Commented: Manav Divekar on 30 Nov 2021
My excel contains multiple sheets. I am trying to return the weight from one sheet for corresponding input of name variable which is in the other sheet of same excel. For the code till now i was able to number of sheets present. how can i reach my end goal. Can I use xlsread instead
function [avgweight] = xls_patientvisits_bp (filename, name)
patients = readtable(filename,'sheet','patients');
visits = readtable(filename,'sheet','visits');
id = patients.patientid(strcmp(patients.Name, name));
avgweight = mean(visits.weight(strcmp(visits.patientid, id)));

Answers (1)

Hiro Yoshino
Hiro Yoshino on 30 Nov 2021
Edited: Walter Roberson on 30 Nov 2021
Use MATLAB >> HOME >> Import Data >> YOUR EXCEL >> Import Option: function
It creates the following code for you to read your excel as a table.
function patientsandvisits = importfile(workbookFile, sheetName, dataLines)
%IMPORTFILE スプレッドシートからデータをインポート
% PATIENTSANDVISITS = IMPORTFILE(FILE) は、FILE という名前の Microsoft Excel
% スプレッドシート ファイルの最初のワークシートからデータを読み取ります。 データを table として返します。
%
% PATIENTSANDVISITS = IMPORTFILE(FILE, SHEET) は、指定されたワークシートから読み取ります。
%
% PATIENTSANDVISITS = IMPORTFILE(FILE, SHEET, DATALINES)
% は、指定されたワークシートから指定された行区間を読み取ります。DATALINES
% を正の整数スカラーとして指定するか、行区間が不連続の場合は正の整数スカラーからなる N 行 2 列の配列として指定します。
%
% 例:
% patientsandvisits = importfile("C:\Users\hyoshino\OneDrive - MathWorks\Desktop\patientsandvisits.xlsx", "patients", [2, 18]);
%
% READTABLE も参照してください。
%
% MATLAB からの自動生成日: 30-Nov-2021 15:06
%% 入力の取り扱い
% シートが指定されていない場合、最初のシートを読み取ります
if nargin == 1 || isempty(sheetName)
sheetName = 1;
end
% 行の始点と終点が指定されていない場合、既定値を定義します
if nargin <= 2
dataLines = [2, 18];
end
%% インポート オプションの設定およびデータのインポート
opts = spreadsheetImportOptions("NumVariables", 5);
% シートと範囲の指定
opts.Sheet = sheetName;
opts.DataRange = "A" + dataLines(1, 1) + ":E" + dataLines(1, 2);
% 列名と型の指定
opts.VariableNames = ["patientid", "Name", "Group", "Age", "Gender"];
opts.VariableTypes = ["double", "string", "categorical", "double", "categorical"];
% 変数プロパティを指定
opts = setvaropts(opts, "Name", "WhitespaceRule", "preserve");
opts = setvaropts(opts, ["Name", "Group", "Gender"], "EmptyFieldRule", "auto");
% データのインポート
patientsandvisits = readtable(workbookFile, opts, "UseExcel", false);
for idx = 2:size(dataLines, 1)
opts.DataRange = "A" + dataLines(idx, 1) + ":E" + dataLines(idx, 2);
tb = readtable(workbookFile, opts, "UseExcel", false);
patientsandvisits = [patientsandvisits; tb]; %#ok<AGROW>
end
end
To access the data in the column of your table, use the syntax as follows:
data = yourTable.yourColumnOfInterest;
  1 Comment
Manav Divekar
Manav Divekar on 30 Nov 2021
what mistake i am making in my code why it is not working?

Sign in to comment.

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!