Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top