for loop with cells and Excel

조회 수: 4 (최근 30일)
Sandra Keks
Sandra Keks 2016년 6월 13일
답변: Guillaume 2016년 6월 13일
Hello,
I would like to organize an Excel spreadsheet, however, in order to do so I need to remove some of the information in the cells. Right now, the info is in the format '123 Main Street, CA ZIP' and I would like to isolate the '23 Main Street' portion. Although I specifically imported the csv Excel file as a column vector from the import menu, it keeps showing up as a 4000 x 1 cell (it's a large spreadsheet). I then 'char'-ed my info, (which is where my mistake is most likely), and created a for loop where I successfully located the comma in each row through indexing (my thought being that if I find the location of the comma I can remove it and everything after i.e index:end). However, this has not been successful. I have included my script and the associated error I keep getting is 'Index exceeds matrix dimensions'.
Any help would be appreciated.
Thanks,
Sandra
ad_new = char(address)
[num_rows, num_cols] = size(ad_new);
x = [];
for index = 1 : num_rows
ad_new = ad_new(index, :)
x = findstr(',', ad_new(index, :));
% ---- Method 1
ad_new(ad_new(index(x)):end) = [];
% ---- Method 2
ad_new = ad_new(index):ad_new(index(x - 1))
end
  댓글 수: 1
Guillaume
Guillaume 2016년 6월 13일
Note that there is a {}Code formatting button which works much better than putting delimiting markers and blank lines between each lines.

댓글을 달려면 로그인하십시오.

답변 (2개)

Marc
Marc 2016년 6월 13일
Unless I don't understand what you are doing, I think the error comes from you using ad_new = ad_ new(....) in the for loop. You destroy the old ad_new. Maybe call the first one ad_old...

Guillaume
Guillaume 2016년 6월 13일
As Marc said, you're replacing your whole char array by just one line of the char array inside the loop.
Also note that findstr is deprecated. You should use strfind instead.
In any case, there's no need for a loop if you just keep the cell array. Note that converting the cell array to char will add blank spaces to the shorter strings.
%address: a cell array of string
ad_new = regexprep(address, ',.*', ''); %remove comma followed by 0 or more of anything.

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by