0

I have a function func(x) which signature is

[v] = func(x)

where v is a function. I wanted to do the following, after reading this post

x= [1:10];
for i=1:length(x)
     v{i} = func(x(i));
end

and I got this error:

Cell contents assignment to a non-cell array object.

What is it that I'm doing wrong?

1 Answer 1

2

Seems v is already a vector, you have to initialise a cell:

v={}

or delete the vector:

clear v

Alternatively you can initialize a cell of the right size, which is faster because it allocates the memory at once:

v=cell(length(x),1);
Sign up to request clarification or add additional context in comments.

9 Comments

I think the fact that v is a vector is irrelevant, I tried this also with "free" names and the result was the same.
@user42864: No, v being is vector is very relevant. You cannot perform cell operations on a vector. Even though MATLAB for the most part is type agnostic, cells and vectors are one of the few instances where you need to make sure that you apply the right syntax to the right kind of variable. What @Daniel said is correct. What I would suggest you do is initialize v to an empty cell array as suggested, then iterate through your loop. It would also help if you placed more code, as the error generated may be related to what is happening before your loop.
@rayryeng thanks, but the reasons I said it is irrelevant because I tried to run the same code with something like u{i} = func(x(j)) and it still returned the same error, after the second iteration. I expected that in the first iteration I'd get that u{1} would be my first vector, u{2} the second etc. In that case it is clear from the first iteration thatu is a cellaray rather then a vector, no?
@user42864: Please update your question and include example code for func which allows us to reproduce the problem. I assumed the v{i} = func(x(i)); assignment causes the problem, but there might be another assignment which is not visible in your question.
Guys, sorry for the trouble, but your remarks were ABSOLUTELY CORRECT while it was I who didn't check it properly. v was used somewhere else and couldn't be implicitly re-assigned. Thank, and sorry for the trouble :)
|

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.