learningMatlab
learningMatlab

Reputation: 229

compare and delete on an array in matlab

I am trying to write a short code to read a .m file(testin1.m) into an array, and search for a particular word( 'auto'). if match is found,delete it. i have the following code, please help me figure out my mistake.

fid = fopen('testin1.m');
 txt = textscan(fid,'%s');
fclose(fid);
m_file_idx = 1;
data=['auto'];
B=cellstr(data);
 for idx = i : length(txt)
 A=txt{i};
 is_auto=isequal(A, B);
 if is_auto==0
 txt{i}=[];
 end
end

if txt{i}=auto then it should delete that row.

Upvotes: 0

Views: 157

Answers (3)

Eitan T
Eitan T

Reputation: 32930

AK4749's answer is absolutely correct in showing where you went wrong. I'll just add an alternative solution to yours, which is shorter:

C = textread('testin1.m', '%s', 'delimiter', '\n');
C = C(cellfun(@isempty, regexp(C, 'auto')));

That's it!

EDIT #1: answer modified to remove the lines that contains the word 'auto', not just the word itself.
EDIT #2: answer modified to accept regular expressions.

Upvotes: 2

shoelzer
shoelzer

Reputation: 10718

When you set txt(i) = [], you changed the length of the array but the loop indexing does not account for the change. You can use logical indexing to avoid the loop and the problem.

Example:

wordToDelete = 'auto';
txt = {'foo', 'bar', 'auto', 'auto', 'baz', 'auto'}
match = strcmp(wordToDelete, txt)
txt = txt(~match)

Output:

txt = 
    'foo'    'bar'    'auto'    'auto'    'baz'    'auto'
match =
     0     0     1     1     0     1
txt = 
    'foo'    'bar'    'baz'

Upvotes: 1

im so confused
im so confused

Reputation: 2121

This is an error i have hit many amany many many times:

when you set txt(i) = [], you change the length of the array. Your for loop condition is no longer valid.

A better option would be to use the powerful indexing features:

A(find(condition)) = [];

or account for the change in length:

A(i) = [];
i--; % <-- or i++, it is too early to think, but you get the idea

EDIT: I just noticed you were also using A in your program. mine was just some random variable name, not the same A you might be using

Upvotes: 2

Related Questions