Can I assign a single value to multiple elements of a cell array without a loop
I'd like to fill out the empty elements of myArray with zeros, but, obviously, the following doesn't work:
myArray = 0
Obviously, I could write a loop, but there has to be a better way!
Thanks for any suggestions!
0 Comments
Accepted Answer
James Tursa on 17 Feb 2015
Direct link to this answer
Cancel Copy to Clipboard
Direct link to this answer
Cancel Copy to Clipboard
Edited: James Tursa on 17 Feb 2015
You almost had the syntax right:
myArray(find(cellfun(@isempty,myArray))) =
Or you can just use logical indexing and skip the find:
myArray(cellfun(@isempty,myArray)) =
1 Comment
Stephen23 on 18 Feb 2015
Direct link to this comment
Cancel Copy to Clipboard
Direct link to this comment
Cancel Copy to Clipboard
Edited: Stephen23 on 18 Feb 2015
The find is completely superfluous and just slows the code down, so use the second version (uses logical indexing ). A slightly faster alternative is to use the overloaded isempty option:
myArray(cellfun( 'isempty' ,myArray)) =
More Answers (1)
Guillaume on 17 Feb 2015
Direct link to this answer
Cancel Copy to Clipboard
Direct link to this answer
Cancel Copy to Clipboard
Your main problem is the confusion between () and <> . Secondly, use logical indexing, rather than find :
myArray(cellfun(@isempty, myArray)) = <0>;0>
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
- América Latina (Español)
- Canada (English)
- United States (English)
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Australia (English)
- India (English)
- New Zealand (English)
- 中国