How to sample single values from field in *non-scalar structure array*?
Mostrar comentarios más antiguos
Hello Matlab experts,
I'm working on the optimization of some code following the Profiler's measurements.
Here, one main bottleneck is the sampling of an individual element on each of the fields contained within the struct array.
For context, let's consider that a non-scalar struct array with uniform mat sparse fields is built as
A = repmat(struct('mat',speye(3)),10,1);
for k = 1:10
A(k).mat = A(k).mat * k;
end
For the sake of simplicity, I'm interested in sampling each field at indexes (i,j) = (2,2) as
col = zeros(10,1);
for k = 1:10
col(k) = A(k).mat(2,2);
end
So that for the next step, I report each sampled point into a column vector.
Thus the expected output is:
>> col
col =
1
2
3
4
5
6
7
8
9
10
Question: is there a much better (hopefully faster) way to do this? (mainly getting rid of the for-loop)
Disclaimer: I have tried converting this struct array into flat array, [A.mat], or into an array of cells, {A.mat}, but I run into the trouble of the sparse nature of the fields (Get warnings with SPFUN). I'm sure there must be a clever way to do this with arrayfun() or cellfun() but the solution eludes me.
8 comentarios
Stephen23
el 25 de Jul. de 2023
"I'm sure there must be a clever way to do this with arrayfun() or cellfun() but the solution eludes me."
Both are likely to be slower than a well-written loop.
Manuel A. Diaz
el 25 de Jul. de 2023
Editada: Manuel A. Diaz
el 25 de Jul. de 2023
"Is there a way to vectorize"
No. Every field contains a different array: in MATLAB it is not possible to write one index into multiple arrays (that you generate with that comma-separated list). It is possible to index into one array.
Manuel A. Diaz
el 25 de Jul. de 2023
Stephen23
el 25 de Jul. de 2023
"Not sure I get you."
This is one array:
A = rand(2,3);
here is some indexing into it:
A(1,3)
In general a comma-separated list in not one array. Therefor it cannot be indexed into like you showed.
Manuel A. Diaz
el 25 de Jul. de 2023
Editada: Manuel A. Diaz
el 25 de Jul. de 2023
Bruno Luong
el 26 de Jul. de 2023
Editada: Bruno Luong
el 26 de Jul. de 2023
You might take a look at this FEX by @Matt J
Manuel A. Diaz
el 26 de Jul. de 2023
Respuesta aceptada
Más respuestas (1)
Bruno Luong
el 25 de Jul. de 2023
Editada: Bruno Luong
el 25 de Jul. de 2023
Just shorter code, not necessary better.
A = repmat(struct('mat',speye(3)),10,1);
for k = 1:10
A(k).mat = A(k).mat * k;
end
col = arrayfun(@(s) full(s.mat(2,2)), A)
1 comentario
Manuel A. Diaz
el 25 de Jul. de 2023
Categorías
Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


