Evaluate variables in external file strings

2019-09-05 04:20发布

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

2条回答
Deceive 欺骗
2楼-- · 2019-09-05 04:43

Try this

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

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

EDIT: To avoid slowdown by eval you can write the string in another m-file and call it instead in the loop. Something like this:

[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

You need the rehash to ask matlab to add newly-created inputMatrix to list of known functions.

查看更多
神经病院院长
3楼-- · 2019-09-05 04:47

After some hints I achieved to come around with the following solution.

%% 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

where read_mixed_csv('input.csv',',') is from Import CSV file with mixed data types.

I am open for better answers!

查看更多
登录 后发表回答