Can I pass table as an argument to a function.?
古いコメントを表示
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
採用された回答
その他の回答 (1 件)
Image Analyst
2020 年 9 月 22 日
0 投票
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
2020 年 9 月 22 日
Not sure why you didn't attach the CSV file in your edit, despite me directly asking for it. That is where the problem lies. Try again top attach, because this works fine:
% DataTable = readtable("mycsv.csv");
X = [1011;1026];
Y = [203;210];
DataTable = table(X, Y)
MyCalulations(DataTable);
function MyCalulations(DataTable)
Xmean=mean(DataTable.X)
Ymean=mean(DataTable.Y)
end
Again, I think it's because DataTable does not have the fields you expect. Leave the semicolon off the readtable() line and see what it puts as the column headers when it reports the table to the command window.
C Mendonsa
2020 年 9 月 22 日
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
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.
カテゴリ
ヘルプ センター および File Exchange で Use Prebuilt MATLAB Interface to C++ Library についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!