2

I am consistently getting an error while writing output in a CSV file using fprintf. I actually want to write my results in a CSV file. I have tried different lengths of the matrix, and I get the same error even with two columns. What's the mistake here and how can I resolve this error?

Sample code:

colname = {'col1' 'col2' 'col3'};
fid = fopen('test.csv','w');
fprintf(fid, '%s, %s, %s\n', colname{1:});
for p=1:5
    % <Some code>
    fname = %reading image name from a directory
    % <Some code>
    val1 = %calculating value1
    val2 = %calculating value2
    datacol = {fname val1 val2};
    fprintf(fid, '%s, %f, %f\n', datacol{p+1:});
end
fclose(fid);

Error:

??? Index exceeds matrix dimensions. at fprintf(fid, '%s, %f, %f\n', datacol{p+1:});

P.S.: Writing "datacol = {fname val1 val2};" as "datacol = {fname,val1,val2};" brought the same error message.

1 Answer 1

2

You are indexing the cell contents of datacol. If I am not mistaken datacol looks sth like this:

{'some_string_for_the_name', 1, 2}

Where 1 and 2 are val1 and val2. During your loop you access datacol{p+1} which obviously is datcol{4} for p = 3. Since your cell only has three elements, indexing a fourth will result in an error. What you probably would like to do is print the lines of val1 and val2, no? Changing your fprintf to

fprintf(fid, '%s, %f, %f\n', datacol{1}, datacol{2}, datacol{3});

should solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.