Home > Blockchain >  use a variable in the readmatrix function in matlab
use a variable in the readmatrix function in matlab

Time:12-09

I have a dataset of train fares across a number of years- my code asks the user to input a year from 2004 and 2022. The code should then display the 3 values of that year from the dataset however it comes up with an error. How can I use the input of the user to determine which sheet data is shown? The code I've used is shown below:

year = input('please select year between 2004 and 2022');
fprintf('you have chosen to see train fares from all sectors in %4.0f',year)
data = readmatrix("train_fares.xlsx",'sheet',year,'range','A1:A3')

Ive tried changing the code to show a specific year instead of the variable 'year' and this returns the data just not what is chosen by the user. This is how my excel spreadsheet is spread out The error message I receive says: Error using readmatrix The 'XLSX' format is not supported in this context. Set the 'UseExcel' parameter to true on Windows with Excel installed to read and write 'XLSB' or 'ODS' files and spreadsheets with interactive features, such as formulas and macros.

Error in plot_data (line 4) data = readmatrix("train_fares.xlsx",'sheet',year,'range','A1:A3')

CodePudding user response:

You are using this

year = input('please select year between 2004 and 2022');

And per the docs for input, it will be evaluated, and therefore something like

>> 2022

Is interpreted by MATLAB as the numeric input 2022

You need to provide the 's' specifier for input, which will prevent the evaluation of your input and leave it as a char. Otherwise when you use it in

data = readmatrix("train_fares.xlsx",'sheet',year,'range','A1:A3')

It's an invalid input, because the 'sheet' input is expected as a char.

So your first line should become

year = input('please select year between 2004 and 2022','s');

CodePudding user response:

Wolfie's answer is correct and I will build upon that in case you need more flexibility (for example, if you want to paramaterize the rows and cols)

cmd = sprintf('data = readmatrix("train_fares.xlsx",''sheet'',''%.0f'',''range'',''A%.0f:A%.0f'')',year,row,col); eval(cmd)

In this execution, year, row, and column are all integers (doubles) and the sprintf command is forming the command string that can be executed with eval()

  • Related