Can I assign a single value to multiple elements of a cell array without a loop

48 Ansichten (letzte 30 Tage)
For example, I have an array that looks like
myArray =
[3] [] [3] []
I'd like to fill out the empty elements of myArray with zeros, but, obviously, the following doesn't work:
myArray{find(cellfun(@isempty,myArray))} = 0
Obviously, I could write a loop, but there has to be a better way!
Thanks for any suggestions!

Akzeptierte Antwort

James Tursa
James Tursa am 17 Feb. 2015
Bearbeitet: James Tursa am 17 Feb. 2015
You almost had the syntax right:
myArray(find(cellfun(@isempty,myArray))) = {0}
Or you can just use logical indexing and skip the find:
myArray(cellfun(@isempty,myArray)) = {0}
  1 Kommentar
Stephen23
Stephen23 am 18 Feb. 2015
Bearbeitet: Stephen23 am 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)) = {0}

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 17 Feb. 2015
Your main problem is the confusion between () and {}. Secondly, use logical indexing, rather than find:
myArray(cellfun(@isempty, myArray)) = {0};

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by