how I can read different text files in Matlab - matlab

How can I read different text files in Matlab.
Considering that there are 33 txt files and that every one should be processed.
Here is part of my code with the error.
textFilename = cell(1,33);
id = cell(1,33);
for k=1:33;
textFilename{k} = fullfile('C:\Users\Desktop\SentimentCode\textfiles',['file' num2str(k) '.txt']);
id{k} = fopen(textFilename{k},'rt');
str{k} = textscan(id{k},'%s%s');
str(str == '.') = '';
str(str == '_') = '';
str(str == '-') = '';
% Remove numbers from text
T =regexprep(str, '[\d]', ' ');
end
and my error is:
??? Undefined function or method 'eq' for input arguments of type 'cell'.
Error in ==> Untitled9 at 23
str(str == '.') = '';

Related

How to generalize Matlab function?

I have a Matlab function. I need to generalize this function. This code’s aim is to check this IndicMPs are in the TableTemp, if it is there, then we extract relevant age limits, such as: Age_Limite_DC, Age_Limite_IT, Age_Limite_Ch and Transfert_Prime_IT_DC. My idea is to generalize, passing parameters to find out the "Type_pret" is.(May be I'm wrong) Since I'm beginner to Matlab can someone help me to encode a more generic function that can be used in a more general context?
function Structure = optimisation_function()
Data = load('Data.mat');
Structure = Data.Structure;
TableTemp = Data.TableTemp;
Age_Limite_DC = zeros(size(Structure,1),1);
Age_Limite_IT = zeros(size(Structure,1),1);
Age_Limite_CH = zeros(size(Structure,1),1);
Transfert_Prime_IT_DC = zeros(size(Structure,1),1);
for IndexMPAL = 1 : length(Structure.AnneeSouscription)
% Determine Type_Pret (Loan Type)
if ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'A'))
Type_Pret = 'A';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'B'))
Type_Pret = 'B';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'C'))
Type_Pret = 'C';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'D'))
Type_Pret = 'D';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'E'))
Type_Pret = 'E';
end
MP_CP = Structure.NomCodeProduit(IndexMPAL);
MP_AnSous = Structure.AnneeSouscription(IndexMPAL);
MP_TypePret = Type_Pret;
IndicCP = strcmp(MP_CP, TableTemp.CodeProduit);
IndicAS = MP_AnSous== TableTemp.AnneeSouscription;
IndicTP = strcmp(MP_TypePret, TableTemp.TypePret);
IndicMP = IndicCP & IndicAS & IndicTP;
if ~any(IndicMP)
Msg = strcat('CodeProduct:',MP_CP{1}, ', Année Souscription:', num2str(MP_AnSous), ', Type Prêt:', MP_TypePret);
error('Error', Msg)
else
Age_Limite_DC(IndexMPAL,1) = TableTemp.Age_Limite_DC(IndicMP,1);
Age_Limite_IT(IndexMPAL,1) = TableTemp.Age_Limite_IT(IndicMP,1);
Age_Limite_CH(IndexMPAL,1) = TableTemp.Age_Limite_CH(IndicMP,1);
Transfert_Prime_IT_DC(IndexMPAL,1)=
TableTemp.Transfert_Prime_IT_DC(IndicMP,1);
end
end
Structure.Age_Limite_DC = Age_Limite_DC;
Structure.Age_Limite_IT = Age_Limite_IT;
Structure.Age_Limite_CH = Age_Limite_CH;
Structure.Transfert_Prime_IT_DC = Transfert_Prime_IT_DC;
end
The if/elseif can be simplified with a cell array:
liststr = {'A','BB','C','D','E'}; % builds a cell array, each cell contains a string
Positive_matches = strfind(liststr,Structure.Type_Pret{IndexMPAL}) % returns a list for each cell of the indices where the element was found (empty if none)
Index = find(~cellfun('isempty', Positive_matches )) % converts the previous list into a logical 0/1 array indicating whether an item was found (1) or not (0)
% if isempty(Index); continue; end % If no index is found, to avoid an error in the next instruction, skips the rest of the code.
Type_Pret = liststr(Index(1));
If the Type_Pret are the same in your list and in Structure? , you can usestrcmp`:
liststr = {'A','B','C','D','E'};
if any(strcmp(Structure.Type_Pret,liststr))
Type_Pret = Structure.Type_Pret
else
% handle error
end
You can also work directly on Structure.Age_Limite_DC without using Age_Limite_DC.

Why isnt this matlab code working?

I'm trying to write a script to remove comment lines from another script file. Here's what I tried:
fid = fopen('correct_answer.m');
aline = {};
counter = 1;
while ~feof(fid)
aline{counter} = fgetl(fid);
if aline{counter}(1) == '%'
aline{counter} = '';
end
counter = counter + 1;
end
This is the error I get:
Attempted to access aline.%cell(1); index out of bounds because numel(aline.%cell)=0.
Error in hw2 (line 8)
if aline{counter}(1) == '%'
If I run it without the while loop it works fine. What's up with this??
Also if you just happen to know a more simple/efficient approach to removing comment lines that would work too ;)
The problem is that you sometimes read empty lines, and you cannot access the first element of empty lines. Additionally you may have comments at the end of a valid line of code, this code should do the trick
fid = fopen('correct_answer.m');
aline = {};
counter = 1;
while ~feof(fid)
aline{counter} = fgetl(fid);
if ~isempty(aline{counter})
k = strfind(aline{counter}, '%');
aline{counter}(k:end) = '';
end
counter = counter + 1;
end

Extraction of data from DWT subband

I am attempting to extract data from a DWT subband. I am able to embed data correctly (I have followed it in the debugger),cal PSNR etc. PSNR rate seem very high 76.2?? however,I am having lot of trouble extracting data back!It is sometimes extracting the number 128?? Can anyone help or have any idea why this is? I would be very thankful.I have been working on this all day & having no luck!I am very curious to know??
Data Embedding:
coverImage = imread('lena.bmp');
message = importdata('minutiaTest.txt');
%message = 'Bifurcations:';
[LL,LH,HL,HH] = dwt2(coverImage,'haar');
if size(message) > size(coverImage,1) * size(coverImage,2)
error ('message too big to embed');
end
bit_count = 0;
steg_coeffs = [4, 4.75, 5.5, 6.25, 7];
for jj=1:size(message,2)+1
if jj > size(message,2)
charbits = [0,0,0,0,0,0,0,0];
else
charbits = dec2bin(message(jj),8)';
charbits = charbits(:)'-'0';
end
for ii=1:8
bit_count = bit_count + 1;
if charbits(ii) == 1
if HH(bit_count) <= 0
HH(bit_count) = steg_coeffs(randi(numel(steg_coeffs)));
end
else
if HH(bit_count) >= 0
HH(bit_count) = -1 * steg_coeffs(randi(numel(steg_coeffs)));
end
end
end
end
stego_image = idwt2(LL,LH,HL,HH,'haar');
imwrite(uint8(stego_image),'newStego.bmp');
Data Extraction:
new_Stego = imread('newStego.bmp');
[LL,LH,HL,HH] = dwt2(new_Stego,'haar');
message = '';
msgbits = '';
for ii = 1:size(HH,1)*size(HH,2)
if HH(ii) > 0
msgbits = strcat (msgbits, '1');
elseif HH(ii) < 0
msgbits = strcat (msgbits, '0');
else
return;
end
if mod(ii,8) == 0
msgChar = bin2dec(msgbits);
if msgChar == 0
break;
end
msgChar = char (msgChar);
message = [message msgChar];
msgbits = '';
end
end
The problem arises from reading your data with importdata.
This command will load the data to an array. Since you have 39 lines and 2 columns (skipping any empty lines), its size will be 39 2. However, the program assumes that your message will be a string. For example, 'i am a string' has a size 1 13. This expectation of the program compared to the data you actually give it creates all sorts of problems.
What you want is to read your data as a single string, where the number 230 is not one element, but 3 individual characters. Tabs and newlines will also be read in as well.
To read your file:
message = fileread('minutiaTest.txt');
After you extract your message, to save it to a file:
fid = fopen('myFilename.txt','w');
fprintf(fid,message);
fclose(fid);

Ini file read and write + add new property + matlab [duplicate]

This question already has an answer here:
Property_value + matlab
(1 answer)
Closed 9 years ago.
How to read and write ini files: I want to add new property to an existing one. I want to write the ini file to temp file and finally add the new property to it. the new property will have head,name,desc, value and layout (like: line 1 & 3)
#---------------
# head
# --------------
[name]% type
# desc
value
fileData = [];
fh = fopen( fileName, 'r' ); % read handle
tname=tempname();
wfh =fopen(tname,'w'); % write handle
line = fgetl(fh);
val = '';
Prop ='';
type = '';
header = '';
desc= '';
while ischar(line)
if strcmpi(line(1),'#') && strcmpi(line(3),'=')
layout = line(2:end);
elseif strcmpi(line(1),'#')&& ~strcmpi(line(3),'=')
header = line(2:end);
else
Prop = regexp(line,{'\[*\w+\]\s*%\s*.*\s*'},'match');
[property data_type] = strtok(Prop,'%')
prop_p = property{1};% property_name
prop_per = regexprep(prop_p,{'\[','\]'},'');
prop = prop_per{1};
Dtype = data_type{1}; % datatype
dtype = strtrim(strrep(Dtype,'%',''));
DATA_type = dtype{1};
end
% How can i define filedname (prop) for the 'layout' and 'header' as they are found in lines before the actual'prop'.
% From command window
% Undefined variable prop.
% Error in ecco2511>add (line 212)
% fileData.(prop{1}).layout = layout;
desc = fgetl(fh); % description
desc = desc(1:end);
line = fgetl(fh);
val = line(1:end);
fileData.(prop).layout = layout;
fileData.(prop).header = header;
fileData.(prop).type = DATA_type;
fileData.(prop).desc = desc;
fileData.(prop).val = val;
line = fgetl(fh); % keep reading
end
if ~isfield( fileData, propName)
fileData.(propName).val = newVal;
fileData.(propName).type = datatype;
fileData.(propName).desc = description;
fileData.(propName).layout = layout;
fileData.(propName).header = header;
else
error ( 'property %s already exists, use set to change its value',propName );
end
fileData = orderfields( fileData );
propNames = fieldnames( fileData );
for ii = 1:numel( propNames )
fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
fprintf(wfh,'\n');
fprintf(wfh,'%s\r',fileData.(propNames{ii}).header);
fprintf(wfh,'\n');
fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
fprintf(wfh,'\n');
fprintf( wfh, '[%s]%s\r', (propNames{ii}),fileData.(propNames{ii}).type);
fprintf(wfh,'\n');
fprintf( wfh,'#%s\r',fileData.(propNames{ii}).desc);
fprintf(wfh,'\n');
fprintf( wfh,'%s\r',fileData.(propNames{ii}).val);
fprintf(wfh,'\n');
end
fclose(fh);
fclose(wfh);
[status,errmsg]= movefile(tname,fileName,'f');
Sounds like you need INI Config from MATLAB File Exchange. It will allow you to read, write, and modify INI style files. I have used it a number of times and it works quite well.

Error while trying to open files in Matlab

My code has 2 parts. First part is an automatic file opening programmed like this :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
for i=1:numberOfFiles
data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end
Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :
reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = cellstr(uigetfile('./*.txt','MultiSelect', 'on'));
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;
It's giving me the following error, after I press OK on the prompt:
Error using cellstr (line 34)
Input must be a string.
Error in FreqVSChampB_no_spec (line 128)
filenames = cellstr(uigetfile('./*.txt','MultiSelect', 'on'));
Anyone has an idea why it's doing that?
You do not need the cellstr command for the output of uigetfile in 'MultiSelect' mode: the output is already in a cellarray form (see doc of uigetfile).