nam
nam

Reputation: 215

Open files with different options

I have two sets of files:

Set 1: { reactant.1.h.txt, reactant.2.h.txt, reactant.3.h.txt }

Set 2: { no2conc.txt, so2conc.txt, coconc.txt }

I am able to open each of them by using

reactanct_1 = fopen('reactant.1.h.txt','r');
no2_conc = fopen('no2conc.txt','r');

Indeed the "1", "2" and "3" in Set 1 refer to NO2, SO2 and CO in Set 2.

I want to write a function such that if I input NO2 into the function, it will open the two specific files in two sets.

So, I design as:

function openfile(chemical)

switch chemical
      case NO2
          id = 1; % for the use of set 1
          string = 'no2'; % for the use of set2
      case SO2
          id = 2; % for the use of set 1
          string = 'so2'; % for the use of set2
      case CO
          id = 2; % for the use of set 1
          string = 'co'; % for the use of set2
end

However, I give a trial that %d refers to my chemicals id and $s refers to the chemical names:

reactanct = fopen('reactant.%d.h.txt', id, 'r');
conc = fopen('%sconc.txt', string,'r');

But matlab returns me Error using fopen.

I appreciate for your help.

Upvotes: 0

Views: 98

Answers (1)

sco1
sco1

Reputation: 12214

The issue lies with how you're passing the filenames to fopen. From the documentation, the (optional) second input to fopen needs to be the file access type, here you have it defined as your chemical ID and chemical name.

You should be able to fix this with a sprintf call to generate your filename:

function openfile(chemical)

switch chemical
      case NO2
          id = 1; % for the use of set 1
          mychem = 'no2'; % for the use of set2
      case SO2
          id = 2; % for the use of set 1
          mychem = 'so2'; % for the use of set2
      case CO
          id = 2; % for the use of set 1
          mychem = 'co'; % for the use of set2
end

reactanct = fopen(sprintf('reactant.%d.h.txt', id), 'r');
conc = fopen(sprintf('%sconc.txt', mychem), 'r');

Upvotes: 1

Related Questions