# Indexing of cell array and a vector

3 Ansichten (letzte 30 Tage)
Sergio Rojas Blanco am 2 Jun. 2024
Hi guys, my problem has been raised before but with some differences.
I have a cell array of indexes, index. Its cells can be zero or vectors with several values. On the other hand I have a data vector, data. I need a cell array, out, that relates data to indexes, preferably without using a loop.
For example:
index = {[0], [0], [5], [0], [6, 7], [0], [0], [1], [0], [0], [0], [ 3]} ;
data = [100, 10, 20, 15, 11, 25, 200, 45];
Desired result:
out = {[0], [0], [11], [0], [25, 200], [0], [0], [100], [0], [0], [20]}
Can somebody help me?
##### 4 Kommentare2 ältere Kommentare anzeigen2 ältere Kommentare ausblenden
Stephen23 am 2 Jun. 2024
Bearbeitet: Stephen23 am 2 Jun. 2024
"I think a loop would be slower, right?"
A well-written FOR-loop would likely be faster than code using CELLFUN, ARRAYFUN, or anything else.
Who taught you the oddly-persistent myth that FOR-loops are slow?
Sergio Rojas Blanco am 3 Jun. 2024
Actually, I don't know the internal process of cellfun or arrayfun. Possibly, they perform a loop and, therefore, it would be difficult to choose the most efficient procedure, but I don't know, and I have assumed that loops take longer. It would have to be checked experimentally.
In any case, I thank you very much for your contributions. They have helped me a lot

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Star Strider am 2 Jun. 2024
One approach —
index = {[0], [0], [5], [0], [6, 7], [0], [0], [1], [0], [0], [0], [ 3]} ;
data = [100, 10, 20, 15, 11, 25, 200, 45];
q = cellfun(@(x) data(x(x>0)), index, 'Unif',0);
Lvc = cellfun(@(x) all(x==0), index, 'Unif',0); % Using 'all' Is Necessary To Make The Logical Indices Work Correctly
out = index;
out(~[Lvc{:}]) = q(~[Lvc{:}])
out = 1x12 cell array
{[0]} {[0]} {[11]} {[0]} {[25 200]} {[0]} {[0]} {[100]} {[0]} {[0]} {[0]} {[20]}
.
##### 2 KommentareKeine anzeigenKeine ausblenden
Sergio Rojas Blanco am 2 Jun. 2024
It works! Thank you very much :D
Star Strider am 2 Jun. 2024
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

R2024a

### Community Treasure Hunt

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

Start Hunting!

Translated by