Error using "csvread" in for loop

2 views (last 30 days)
BAN
BAN on 22 Mar 2015
Commented: BAN on 23 Mar 2015
Hello,
I'm trying to extract one row at a time from csv file and save it in another file and use it to achieve my task. I've created a MATLAB GUI to select a csv file and perform some operations on each row and display it in UI. I could do it for one row at a time. But, in a loop !! :( It throws out error.
To extract the first row and save it to another file I tried using
csvwrite('num.csv', csvread(filename(0, 0, [0 0 0 4]))
csvread('num.csv')
(I've 5 columns in my file). I was able to extract the first row successfully.
I've around 900 rows in my csv file. I tried using for loop to repeat this for every row.
Here's part of my code.
for i = 0:899
{
csvwrite('num.csv', csvread(filename(i, 0, [i 0 i 4]))
csvread('num.csv')
% few other instructions to perform some operations on the extracted row
}
It throws out an error that,
Error using csvwrite
Too many output arguments
Error in the line csvwrite('num.csv', csvread(filename(i, 0, [i 0 i 4]))
Error while evaluating uicontrol callback
Please help me out in resolving this issue.

Answers (1)

dpb
dpb on 23 Mar 2015
Matlab is NOT C...
for i = 0:899
{
csvwrite('num.csv', csvread(filename(i, 0, [i 0 i 4]))
...
}
The "curlies" above try to convert that inside them into a cell array element which isn't possible given the content and that's what's giving the error. I've certainly never seen anybody try this in Matlab before and I suspect TMW developers never expected it, hence the somewhat cryptic error.
See
doc for
for proper construction of for...end loops in Matlab.
After that, using csvread this way is a_bad_idea (tm) even if you can get it to work; it's extremely overhead intensive. I'd suggest reading the file and selecting the data from it that you want in memory instead. If you want to do something to each element or row in Matlab, the way to do that is almost always to do it on the entire array in "one swell foop"; that's wny the "Matrix" in Matlab; it is written specifically to do things on matrices. It's what the documentation call "vectorization".
Show us what it is you want to do to the file and we can probably show a much faster way...
  1 Comment
BAN
BAN on 23 Mar 2015
I got desired output just by taking out curly braces. :D :D
Thanks for your help :) :)

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!