Formating a structs value

1 次查看(过去 30 天)
Hi!
i'm looking for a way to format the values fields in a struct to double.
The problem is that the variable names changes for each use-case. and i can't figure out how to write the part to format the structs value with varying variable names.(Clarifications in whole code below).
Example:
in essens i want to be able to use: double(answer.v1) but make it so that it accepts varying variables. i.e. double(answer.[variable-name-here]) (this is meant to visualize the problem, i know i can't use a struckt field call directly as shown in the example)
Current Data:
answer =
struct with fields:
v1: 9.9444846729423123340574462949553 + 0.31860970311368573497465604634323i
v2: 1.7861453053342988172821626840454 - 0.39584841902003379193820902727492i
Wanted Data:
double(answer.v1)
ans =
9.9445 + 0.3186i
double(answer.v2)
ans =
1.7861 - 0.3958i
Whole Code:
clc, clear, close all;
% Example equation 1: (12-v1)/500 == (v1/10e3i) + (v1-v2)/2e3
% Example equation 2: (v1-v2)/2e3 == v2/(-5e3i) + 4e-3
% variables used: v1 v2
prompt = {'Number of Equations:','Number of variables:'};
dlgtitle = 'Calc. of Node Voltage:';
dims = [1 50];
definput = {'2','2'};
nodeEquations = inputdlg(prompt,dlgtitle,dims,definput); %prompt user for number of variables and equations
%Input for number of variables
for i=1:numel(zeros(1,str2double(nodeEquations(2))))
vartemp{i} = 'Unknown (Exact match to Equations!)'; % Creates temporary array for each unknown variable
end
%Input for number of equations
for i=1:numel(zeros(1,str2double(nodeEquations(1))))
temparr{i} = 'Equation (Exact match to Unknown variables!)'; % Creates a temporary array for each equation
end
x = inputdlg(temparr); %Prompts user for the equations
y = inputdlg(vartemp); %Prompts user for Unknown variables
symbols = cell2sym(y);
equations = str2sym(x);
answer = solve(equations)

采纳的回答

Aquatris
Aquatris 2024-4-9
编辑:Aquatris 2024-4-9
Something like this maybe:
syms v1 v2 ;
symbols = [v1;v2];
equations = [3/125 - v1/500 == v1*(0.0005 - 0.0001i) - 0.0005*v2
0.0005*v1 - 0.0005*v2 == 0.004 + v2*0.0002i];
answer = solve(equations);
% get all the field names within 'answer'
fNames = fieldnames(answer);
% convert solution to doubles and store in 'sol' variable
for i = 1:length(fNames)
sol.(fNames{i}) = double(answer.(fNames{i}));
end
sol
sol = struct with fields:
v1: 9.9445 + 0.3186i v2: 1.7861 - 0.3958i
  2 个评论
Stephen23
Stephen23 2024-4-10
编辑:Stephen23 2024-4-10
The FOR-loop can be replaced with:
sol = structfun(@double,answer)
or
sol = structfun(@double,answer, 'UniformOutput',false)
sverre Kvist
sverre Kvist 2024-4-10
Fantastic, exactly what i was looking for.
Thank you :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by