Clear Filters
Clear Filters

Data from excel with operators

4 views (last 30 days)
I have a excel sheet with two coloumns. One has a name other has the corresponding mass to it. I have used the correspèonding line to read it and find the position of the name. But when i am trying to fing the mass to the corresponding name as shown below it is not able to store it in the memory. In the excel i have the mass values as 1.989*10^30. this seems to affect the code as the same code works fine when the cells in the excel has just numeric values.
majbod = 'Sun';
minbod = 'Earth';
majbodin = readtable("Major_and_Minor_Bodies.xlsx","Sheet",1);
minbodin = readtable("Major_and_Minor_Bodies.xlsx","Sheet",2);
MAJORBODY = table2array(majbodin(:,"Major_Body"));
MINORBODY = table2array(minbodin(:,"Minor_Body"));
mmaj = table2array(majbodin(:,"Mass"));
mmin = table2array(minbodin(:,"Mass"));
selected_majbody = find(strcmp(MAJORBODY,majbod));
selected_minbody = find(strcmp(MINORBODY,minbod));
M = mmaj(selected_majbody);
m = mmin(selected_minbody);
disp([M ;m])
I have attached the excel file with the code. Please help me with this.
Is there a better way to write the code compared to the way which I wrote?

Accepted Answer

Cris LaPierre
Cris LaPierre on 11 May 2020
Edited: Cris LaPierre on 11 May 2020
The main issue you are having is that your numbers are not numbers, but text. If possible, update your numbers in Excel to use this notation instead: 1.989E+30
That way, the mass can be read in as a number. Otherwise, convert the text representation of the number to a number.
Is there an easier way? Yes! Use the table to your advantage. Make the object the row name, and then reference it by name.
opts = spreadsheetImportOptions("NumVariables", 2);
% Specify sheet and range
opts.Sheet = "Sheet2";
opts.DataRange = "A2";
% Specify column names and types
opts.VariableNames = ["Minor_Body", "Mass"];
opts.VariableTypes = ["categorical", "string"];
minorBodies = readtable("Major_and_Minor_Bodies.xlsx", opts,"ReadRowNames",true);
%This next line replaces the " *10^" with "e"
Now when you want to reference a mass, use the rowname.
ans = 5.6830e+26
Cris LaPierre
Cris LaPierre on 12 May 2020
It's not 0, it's 0.000e+26
1.0e+26 *
The value is being hidden because the magnitude of the other values are so high. Remove the semicolon from the end of the line that assigns a value to rma to see it.
Lepakshi Ramkiran
Lepakshi Ramkiran on 12 May 2020
yup that was it. thanks a lot.

Sign in to comment.

More Answers (0)


Find more on Data Import from MATLAB in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!