how can I extract values from a struct matrix that contains only one value to make single matrix from it?
Mostrar comentarios más antiguos
I have This code down below that contains one value . I want extract the values so that I can plot a line plot . Instead of a line plot I can only obtain a plot down below
S=load('U_at_right_top');U_at_right_top=S.U_at_right_top;%edit Rik: added load
n=1000
for j=1:n
fnu=sprintf('u%d',j);
fnv=sprintf('v%d',j);
u = U_at_right_top.(fnu).u;
%v = V_at_right_top.(fnv).v;
plot(j,u,'x--')
hold on
end
1 comentario
S = load('U_at_right_top');
S = S.U_at_right_top
S.u1
Features of this data that should be avoided if possible:
- Naming the variable the same as the filename. Avoid forcing lots of meta-data into the variable name: a much better (simpler, more reliable, more generalizable) approach is to store the meta-data in their own variables, e.g. in a variable named "position" or similar. Then your code will be simpler, more robust and easy to generalize.
- Lots and lots and lots of fields with pseudo-indices in their names. Replace awkward pseudo-indices with one array and actual indexing. Your code will be simpler, more robust, and much more efficient.
- Lots and lots and lots of scalar structures with one field each of which contains exactly one numeric scalar. Ouch!
Whenever meta-data is being forced into names of something then processing that data gets harder.
F = @(n)S.("u"+n);
A = [arrayfun(F, 1:numel(fieldnames(S))).u] % your data should be in an array
Respuesta aceptada
Más respuestas (2)
Using numbered field names is a bad idea. It is almost as bad as using numbered variable names directly.
The solution is to use arrays. This could have been a struct array.
S=load('U_at_right_top');U_at_right_top=S.U_at_right_top;
u = zeros(1,numel(fieldnames(U_at_right_top)));
for n=1:numel(u)
fnu=sprintf('u%d',n);
u(n) = U_at_right_top.(fnu).u;
end
plot(1:numel(u),u,'x--')
Jinal
el 5 de Feb. de 2024
Hi hsnHkl
You can store your struct values in an array, 'u' and use the array to create a line plot outside the for loop.
I am attaching the code snippet for your reference.
n = 1000;
u = 0;
for j=1:n
fnu=sprintf('u%d',j);
u(j) = U_at_right_top.(fnu).u;
end
plot(u);
Attaching documentation of 2-D line plot for your reference.
Categorías
Más información sobre Logical 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!


