Error Using a loop: Conversion to double from cell is not possible.
Show older comments
Hello everyone,
On executing following code:
for w = 1:10
PN = PName{w};
CS = CSize{w};
Project = [PN CS];
Project = sortrows(Project,1);
Project = Project(11:end,1:end);
Proj(w) = Project;
end
I am getting error: Conversion to double from cell is not possible..
Code is running well till Project = Project(11:end,1:end);
Size of Project is: 4227x2 cell.
Error is while assigning a values to a new variable using a loop at Proj(w) = Project;
Any help would be appreciated :-)
Regard,s
Waqar Ali
3 Comments
Guillaume
on 10 Jul 2019
Well, as you state Prorject is a cell array. From the error message, we can deduce that Proj is a matrix of doubles. So, of course you can't store a whole cell array as an element of a matrix.
Since you haven't said what you're trying to do, we can't tell you how to fix it, other than not trying to store cell arrays in matrices.
Waqar Ali Memon
on 10 Jul 2019
Stephen23
on 10 Jul 2019
"I want to create a new variable ... I should get new variable with name Proj1..."
Dynamically accessing variable names is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
In contrast indexing is simple, neat, easy to debug, and very efficient. You should use indexing, just like madhan ravi showed in their answer.
Accepted Answer
More Answers (2)
madhan ravi
on 10 Jul 2019
Proj = cell(10,1); % outside loop
Proj{w} = ... % inside loop , leave the rest unchanged
3 Comments
Waqar Ali Memon
on 10 Jul 2019
madhan ravi
on 10 Jul 2019
See https://in.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval why it's a terrible terrible idea
Stephen23
on 10 Jul 2019
+1 simple and efficient MATLAB solution.
Waqar Ali Memon
on 10 Jul 2019
1 vote
1 Comment
Peter Jarosi
on 10 Jul 2019
Waqar Ali Memon : You're very welcome!
I totally agree with programmer gurus madhan ravi, Guillaume , and Stephen Cobeldick. It is not recommended using dinamically changed variable names, and string operations instead of numbers, especially when we develope big applications. I appreciate their comments.
But sometimes we have to break rules, we need ugly tricks in order to solve our small problems quickly. :-)
Good luck!
Categories
Find more on Matrix Indexing 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!