for loop with cells and Excel

4 vues (au cours des 30 derniers jours)
Sandra Keks
Sandra Keks le 13 Juin 2016
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 commentaire
Guillaume
Guillaume le 13 Juin 2016
Note that there is a {}Code formatting button which works much better than putting delimiting markers and blank lines between each lines.

Connectez-vous pour commenter.

Réponses (2)

Marc
Marc le 13 Juin 2016
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 le 13 Juin 2016
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.

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by