I am trying to solve a system of nonlinear equations and compute the grouped mean of a dataset in MATLAB R2024b
Afficher commentaires plus anciens
Question:
My goal is to:
Solve the following nonlinear equations:
x2+y2−4=0
xy−1=0
Compute the grouped mean.
Generate two plots: a scatter plot for the solutions to the equations and a bar chart for the grouped mean values.
However, I am facing errors when trying to compute the grouped mean using varfun.
MATLAB throws an error in varfun, saying that "A grouping variable must be a column vector or a character array".
I need the grouped mean values for Value, but the function does not seem to work. How can I fix the error in varfun? Is it better to use grouptransform instead?
How can I correctly generate the two plots (scatter for equation solutions, bar for grouped means) without errors?
clc; clear; close all;
syms x y
eq1 = x^2 + y^2 - 4;
eq2 = x*y - 1;
sol = solve([eq1, eq2], [x, y]);
if isempty(sol.x)
error("No real solutions found!");
end
x_vals = double(sol.x);
y_vals = double(sol.y);
data = table([1; 2; 3; 4]', [10; 20; 30; 40]', 'VariableNames', ["ID", "Value"]);
groupedData = varfun(@mean, data, 'GroupingVariables', "ID", 'InputVariables', "Value");
fig = figure;
tiledlayout(2, 1);
nexttile
scatter(x_vals, y_vals, 'filled')
title("Solutions to the Nonlinear Equations")
xlabel("x values"), ylabel("y values")
nexttile
bar(groupedData.ID, groupedData.mean_Value, 'FaceColor', 'cyan')
title("Grouped Mean Values")
xlabel("ID"), ylabel("Mean Value")
exportgraphics(fig, "plot_output.png", "Resolution", 300);
Réponse acceptée
Plus de réponses (1)
Hi @Likith
I understand you are trying to solve a couple of nonlinear equations.
I am able to reproduce the error occurred to you. As the error states, the input value of “Grouping Variables” should be a column vector.
Refer to the below documentation link for more details.
On inspecting "data", “data[“ID”]” is a row vector. So, you can follow the below code to initialise data with entries as column vectors.
data = table([1; 2; 3; 4], [10; 20; 30; 40], 'VariableNames', ["ID", "Value"]);
Hope it helps!
1 commentaire
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!