Can I pass table as an argument to a function.?

조회 수: 39 (최근 30일)
C Mendonsa
C Mendonsa 2020년 9월 22일
댓글: Ameer Hamza 2020년 9월 22일
Hi,
Currently I am working on migration of MATLAB scripts to C++ code.
I encountered a problem with the datastucture table. Basically I am reading a CSV file using readtable and stored it in a table DataTable. I want to send this table to a function which uses the DataTable for some calculations. But when I tried to access the members of the DataTable this is where the problem starts, The coder app is not allowing me to access the parameters in the DataTable and is showing the error "When indexing a table using variable names, the names of the table variables must be constant.". Example code is below
mycsv.csv is a simple csv file with feilds as X and Y
X,Y
1011,203
1026,210
DataTable = readtable("mycsv.csv");
MyCalulations(DataTable);
function MyCalulations(DataTable)
Xmean=mean(DataTable.X);
Ymean=mean(DataTable.Y)
end

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 22일
편집: Ameer Hamza 2020년 9월 22일
See this answer here: https://www.mathworks.com/matlabcentral/answers/572815-matlab-coder-table-variables-must-be-constant. It will be easier if you index the table using numeric values. For example
function MyCalulations(DataTable)
Xmean=mean(DataTable{:,1});
Ymean=mean(DataTable{:,2})
end
The C++ code is generated correctly.
These are some useful links:

추가 답변 (1개)

Image Analyst
Image Analyst 2020년 9월 22일
Can you attach "mycsv.csv" so we can try it? It might call the fields "Var1" and "Var2" instead of X and Y since you didn't specify field names for the table.
  댓글 수: 4
Image Analyst
Image Analyst 2020년 9월 22일
편집: Image Analyst 2020년 9월 22일
I don't have the Coder Toolbox like you do, so I can't help. Sorry. Contact tech support.
By the way, this works if you set ReadVariableNames to true:
DataTable = readtable("mycsv.csv", 'ReadVariableNames', true)
MyCalculations(DataTable)
function [Xmean, Ymean] = MyCalculations(DataTable)
Xmean = mean(DataTable.X)
Ymean = mean(DataTable.Y)
end
Ameer Hamza
Ameer Hamza 2020년 9월 22일
For me, even this works fine
DataTable = readtable("mycsv.csv")
MATLAB automatically read the variable name. I am using R2020a. Maybe this behaviour was changed in some recent release.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by