0

Issue

I want to import a CSV file with mixed data types of numbers and variables/symbols. The import part was already discussed in Import CSV file with mixed data types.

Description

The CSV file here contains only 2x2 formulas (but in general 64x64 and I evaluate it 1'000'000 times). The problem that I was facing is the evaluation of the cells. This can not be done in the same way.

The matlab code is something like

% Parameter initialization
vector1 = ones(1e6);
a=1;
b=2;
c=3;
d=4;

% Formula calculation
vector2(1)=import('input000001.csv');

where my minimal input file input000001.csv contains some formula, as e.g.:

a*vector1(1),2*vector1(1)/b
c+vector1(1),3*vector1(1)^d
4

2 回答 2

1

尝试这个

[a b c d] = deal(1,2,3,4);

data = strcat(importdata('input.csv', sprintf('\n')), ';');
Matrix = eval(['[' data{:} '[]]']);

编辑:为了避免减速,eval您可以将字符串写入另一个 m 文件并在循环中调用它。像这样的东西:

[a b c d] = deal(1,2,3,4);

matDef = regexprep(fileread('input.csv'), {'(\r\n|\r|\n)' ';^'}, {';' ''});
f = fopen('inputMatrix.m', 'w');
fwrite(f, ['Matrix = [' matDef '];'])
fclose(f);
rehash

for k=1:100000,
    inputMatrix
end

您需要rehash要求 matlab 将新创建的函数添加inputMatrix到已知函数列表中。

于 2013-06-26T21:58:15.297 回答
0

经过一些提示后,我实现了以下解决方案。

%% Initialization
a=1;
b=2;
c=3;
d=4;

%% Procedure for input and evaluation
Temp = cell(read_mixed_csv('input.csv',','));
[imax,jmax]=size(Temp);
Matrix = zeros(imax,jmax);
for i = (1:imax)
    for j = (1:jmax)
        Matrix(i,j) = eval(Temp{i,j});
    end
end

哪里read_mixed_csv('input.csv',',')来自Import CSV file with mixed data types

我愿意寻求更好的答案!

于 2013-06-26T19:03:19.637 回答