Cannot convert EditField(text) into arrays or matrix

7 views (last 30 days)
Hello, I try to make a project for colledge. My task is to enter in the EditFields(Text) two separate values for the 3 examples below. If it's a scalar, I have to enter 2 numbers, if it's a vector(array) to enter 2 arrays and if it's a matrix, to enter 2 matrixes. Everything went well until I try to enter 2 arrays or matrixes in the EditFields(Text). I tried different ways like [1, 2, 3] or [1 2 3] or 1 2 3 etc, but everytime I got either the error 'Error setting property 'Data' of class 'Table':
Data within a cell array must have size [1 1]' or 'Error setting property 'Data' of class 'Table': Values within a cell array must be numeric, logical, or char' . The results should be shown into the table from bottom right. I tried to convert the values like this:
newRow = {selectedFunction, result};
if isnumeric(result)
newRow{2} = result;
elseif ischar(result)
newRow{2} = {result};
else
uialert(app.UIFigure, 'Eroare: Tip de date neacceptat pentru adăugarea la tabel!', 'Eroare', 'Icon', 'error');
return;
end
app.ResultTable.Data = [app.ResultTable.Data; newRow];
Any suggestions? It's pretty urgent, my deadline is in 2 days to present the project. Many thanks!
I tried to

Answers (1)

Voss
Voss on 28 Jan 2024
Edited: Voss on 30 Jan 2024
Here (attached and reproduced below) is a simple GUI where you can enter scalars, vectors, or matrices, and their sum will be shown in a new row in the table. Note that the dimensionality of the inputs does not have to be explicitly specified (e.g., with a radiobutton selection) because the program works the same whatever you enter. You can run this program yourself and see how it works, and adapt your app as needed.
function array_plus_table_demo()
f = uifigure('AutoResizeChildren','off');
ed1 = uieditfield(f,'text');
ed2 = uieditfield(f,'text');
btn = uibutton(f,'Text','Go','ButtonPushedFcn',@cb_go);
t = uitable(f,'Data',cell(0,2),'ColumnName',compose('Column %d',[1 2]),'RowName',{});
f.SizeChangedFcn = @scf;
scf()
function cb_go(~,~)
val1 = str2num(ed1.Value,'Evaluation','restricted');
val2 = str2num(ed2.Value,'Evaluation','restricted');
if ~isequal(size(val1),size(val2))
uialert(f,'Inputs must be the same size','Error','Icon','error');
return
end
str = mat2str(val1+val2);
t.Data(end+1,:) = {'plus',str};
end
function scf(~,~)
ppos = f.Position;
space = 10;
wh = [85 26];
xy = ppos([3 4])./[4 2]-wh./[2 1]-[0 space];
dy = wh(2)+space;
ed1.Position = [xy wh];
ed2.Position = [xy wh]-[0 dy 0 0];
btn.Position = [xy wh]-[0 2*dy 0 0];
wh = max(0,ppos([3 4])./[2 1]-2*space);
t.Position = [ppos(3)-space-wh(1) space wh];
end
end
  2 Comments
ALBESCU
ALBESCU on 29 Jan 2024
Edited: Voss on 29 Jan 2024
Hello @Voss,
Thank you very much for your help. I can now introduce Arrays and Matrices into the EditFields(text) and they are recognized and shown into the axes. The only thing that doesn't work is that the results of any Array or Matrices operations are not shown into the result table as you can see in the attached screenshot. Only when using numeric values, the results are showing.
These are the tasks of the project: Study the functions plus, uplus, minus, uminus, times, rdivide, Idivide, power, mtimes and build a GUI application in MATLAB using AppDesigner. The GUI is required to include: • A list-type graphic object (ListBox) with the names of the functions for selecting the desired function. • Graphical objects needed to read input arguments like this: • 3 radio buttons specifying whether the reading arguments are scalars, vectors or matrices • When evaluating the expressions, it is checked if the reading is correct for the input data and if the operands have the same size. Otherwise, some error messages are required to be displayed through modal dialog boxes. • A Table graphic object for displaying the results • An axis-type graphic object in which the values of the input arguments and the result will be represented with different colors. If you work with scalars, markers of different colors will be drawn, if you work with vectors, only lines of different colors will be used, if they are matrices, then the representation is done only for the result using the Matlab imshow function.
Here is the whole code for reference:
classdef app1 < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
Operand2EditField matlab.ui.control.EditField
Label_2 matlab.ui.control.Label
Operand1EditField matlab.ui.control.EditField
Label matlab.ui.control.Label
ExecutButton matlab.ui.control.Button
ResultTable matlab.ui.control.Table
ArgumentTypeButtonGroup matlab.ui.container.ButtonGroup
MatriceButton matlab.ui.control.RadioButton
VectorButton matlab.ui.control.RadioButton
ScalarButton matlab.ui.control.RadioButton
FunctionListBox matlab.ui.control.ListBox
FunctionListBoxLabel matlab.ui.control.Label
UIAxes matlab.ui.control.UIAxes
end
methods (Access = private)
% Funcție pentru inițializarea componentelor
function initializeComponents(app)
% Creare UIFigure și ascundere până la crearea tuturor componentelor
app.UIFigure = uifigure('Visible', 'off');
app.UIFigure.Position = [100, 100, 640, 480];
app.UIFigure.Name = 'Calculator App';
% Creare ListBox pentru funcții
app.FunctionListBox = uilistbox(app.UIFigure);
app.FunctionListBox.Items = {'plus', 'uplus', 'minus', 'uminus', 'times', 'rdivide', 'ldivide', 'power', 'mtimes'};
app.FunctionListBox.Position = [20, 300, 100, 100];
app.FunctionListBox.Value = 'plus';
% Creare ButtonGroup pentru tipul de argument
app.ArgumentTypeButtonGroup = uibuttongroup(app.UIFigure);
app.ArgumentTypeButtonGroup.SelectionChangedFcn = createCallbackFcn(app, @radioButtonsValueChanged, true);
app.ArgumentTypeButtonGroup.Title = 'Argument Type';
app.ArgumentTypeButtonGroup.Position = [150, 290, 120, 120];
% Creare RadioButton pentru Scalar
app.ScalarButton = uiradiobutton(app.ArgumentTypeButtonGroup);
app.ScalarButton.Text = 'Scalar';
app.ScalarButton.Position = [10, 70, 100, 22];
app.ScalarButton.Value = true;
% Creare RadioButton pentru Vector
app.VectorButton = uiradiobutton(app.ArgumentTypeButtonGroup);
app.VectorButton.Text = 'Vector';
app.VectorButton.Position = [10, 40, 100, 22];
% Creare RadioButton pentru Matrice
app.MatriceButton = uiradiobutton(app.ArgumentTypeButtonGroup);
app.MatriceButton.Text = 'Matrix';
app.MatriceButton.Position = [10, 10, 100, 22];
% Creare Table pentru afișarea rezultatelor
app.ResultTable = uitable(app.UIFigure);
app.ResultTable.Position = [300, 20, 200, 200];
% Creare Button pentru executarea operației
app.ExecuteButton = uibutton(app.UIFigure, 'Text', 'Execute', 'Position', [20, 250, 100, 30], 'ButtonPushedFcn', createCallbackFcn(app, @executeButtonPushed, true));
% Afișare UIFigure după crearea componentelor
app.UIFigure.Visible = 'on';
end
% Funcție pentru conversia rezultatului în formatul corect pentru tabel
function formattedResult = formatResultForTable(app, result)
% Obține tipul de argument selectat (Scalar, Vector, Matrice)
argumentType = app.ArgumentTypeButtonGroup.SelectedObject.Text;
switch argumentType
case 'Scalar'
% Pentru scalar, nu este nevoie de conversie
formattedResult = result;
case 'Vector'
% Pentru vector, convertim rezultatul la formatul potrivit
formattedResult = {result};
case 'Matrice'
% Pentru matrice, convertim rezultatul la formatul potrivit
formattedResult = {result};
otherwise
% În cazul în care nu se specifică tipul de argument, păstrăm rezultatul nemodificat
formattedResult = result;
end
end
end
% Callbacks that handle component events
methods (Access = private)
% Value changed function: FunctionListBox
function listBoxValueChanged(app, event)
% Actualizați codul aici în funcție de selecția din ListBox
selectedFunction = app.FunctionListBox.Value;
disp(['Funcția selectată: ', selectedFunction]);
end
% Selection changed function: ArgumentTypeButtonGroup
function radioButtonsValueChanged(app, event)
% Actualizați codul aici în funcție de tipul de argument selectat
isScalar = app.ScalarButton.Value;
isVector = app.VectorButton.Value;
isMatrix = app.MatriceButton.Value;
disp(['Tipul de argument selectat: Scalar - ', num2str(isScalar), ', Vector - ', num2str(isVector), ', Matrice - ', num2str(isMatrix)]);
end
% Button pushed function: ExecutButton
function ExecuteButtonPushed(app, event)
disp('Butonul de Execuție a fost apăsat.');
% Verifică validitatea datelor de intrare
if ~checkInputValidity(app, event, app.ArgumentTypeButtonGroup.SelectedObject.Text)
return;
end
% Obține funcția selectată din ListBox
selectedFunction = app.FunctionListBox.Value;
% Obține tipul de argument (Scalar, Vector, Matrix)
argumentType = app.ArgumentTypeButtonGroup.SelectedObject.Text;
% Obține valorile argumentelor
operand1 = app.Operand1EditField.Value;
operand2 = app.Operand2EditField.Value;
function dataType = evaluateDataType(value)
% Verifică dacă valoarea este numerică
if ~isnan(str2double(value))
dataType = 'numeric';
else
% Încercă interpretarea ca vector sau matrice
vectorValue = str2num(value);
matrixValue = str2mat(value);
if ~isempty(vectorValue) && isvector(vectorValue)
dataType = 'vector';
elseif ~isempty(matrixValue) && ismatrix(matrixValue)
dataType = 'matrix';
else
dataType = 'unknown';
end
end
end
% Implementează verificarea corectitudinii citirii și a dimensiunilor operandilor
function isValid = checkInputValidity(app, ~, argumentType)
% Verifică corectitudinea citirii datelor de intrare
try
operand1 = app.Operand1EditField.Value;
operand2 = app.Operand2EditField.Value;
catch
% Afișează casetă de dialog modală pentru eroare la citire
uialert(app.UIFigure, 'Eroare la citirea datelor de intrare!', 'Eroare', 'Icon', 'error');
isValid = false;
return;
end
% Verifică dacă operandii pot fi convertiți în vectori sau matrice
try
switch argumentType
case 'Scalar'
% Nu este nevoie de conversie pentru scalari
case 'Vector'
operand1 = str2num(operand1);
operand2 = str2num(operand2);
case 'Matrice'
operand1 = str2num(operand1);
operand2 = str2num(operand2);
otherwise
% Tip de argument necunoscut
isValid = false;
return;
end
catch
% Afișează casetă de dialog modală pentru eroare la conversie
uialert(app.UIFigure, 'Eroare: Nu se pot converti operanzii în vectori sau matrice!', 'Eroare', 'Icon', 'error');
isValid = false;
return;
end
% Verifică dimensiunea operandilor
switch argumentType
case 'Scalar'
% Nu este nevoie de verificări suplimentare pentru scalari
case 'Vector'
% Verifică dacă operandii sunt vectori de aceeași lungime
if ~(isvector(operand1) && isvector(operand2) && numel(operand1) == numel(operand2))
% Afișează casetă de dialog modală pentru dimensiuni diferite
uialert(app.UIFigure, 'Eroare: Dimensiuni diferite pentru vectori!', 'Eroare', 'Icon', 'error');
isValid = false;
return;
end
case 'Matrice'
% Verifică dacă operandii sunt matrice de aceeași dimensiune
if ~(ismatrix(operand1) && ismatrix(operand2) && isequal(size(operand1), size(operand2)))
% Afișează casetă de dialog modală pentru dimensiuni diferite
uialert(app.UIFigure, 'Eroare: Dimensiuni diferite pentru matrice!', 'Eroare', 'Icon', 'error');
isValid = false;
return;
end
otherwise
% Tip de argument necunoscut
% Afișează casetă de dialog modală pentru tip de argument necunoscut
uialert(app.UIFigure, 'Eroare: Tip de argument necunoscut!', 'Eroare', 'Icon', 'error');
isValid = false;
return;
end
% Dacă toate verificările trec, atunci datele de intrare sunt considerate valide
isValid = true;
end
% Obține valorile argumentelor
operand1 = app.Operand1EditField.Value;
operand2 = app.Operand2EditField.Value;
% Verifică dacă câmpurile nu sunt goale
if isempty(operand1) || isempty(operand2)
% Afișează casetă de dialog modală pentru câmpuri goale
uialert(app.UIFigure, 'Eroare: Unul sau ambele câmpuri sunt goale!', 'Eroare', 'Icon', 'error');
return;
end
% Evaluare tip de date pentru operand1 și operand2
typeOperand1 = evaluateDataType(operand1);
typeOperand2 = evaluateDataType(operand2);
% Verifică dacă tipurile de date sunt aceleași pentru a permite operațiile
if ~isequal(typeOperand1, typeOperand2)
% Afișează casetă de dialog modală pentru tipuri de date diferite
uialert(app.UIFigure, 'Eroare: Tipuri de date diferite pentru operandi!', 'Eroare', 'Icon', 'error');
return;
end
disp(['Operand1 înainte de conversie: ', operand1]);
disp(['Operand2 înainte de conversie: ', operand2]);
% Conversie la tip numeric sau păstrarea valorilor inițiale
try
switch typeOperand1
case 'numeric'
operand1 = str2double(operand1);
operand2 = str2double(operand2);
case 'vector'
operand1 = str2num(operand1);
operand2 = str2num(operand2);
case 'matrix'
operand1 = str2num(operand1);
operand2 = str2num(operand2);
otherwise
% Tip de date necunoscut
uialert(app.UIFigure, 'Eroare: Tip de date necunoscut!', 'Eroare', 'Icon', 'error');
return;
end
% Verifică dacă conversia a eșuat
if any(isnan([operand1(:); operand2(:)]))
% Afișează casetă de dialog modală pentru eroare la conversie
uialert(app.UIFigure, 'Eroare: Nu se pot converti operanzii în numere!', 'Eroare', 'Icon', 'error');
return;
end
catch
% Afișează casetă de dialog modală pentru eroare la conversie
uialert(app.UIFigure, 'Eroare: Nu se pot converti operanzii în numere, vectori sau matrice!', 'Eroare', 'Icon', 'error');
return;
end
% Obține funcția selectată din ListBox
selectedFunction = app.FunctionListBox.Value;
% Evaluare și afișare rezultat în funcție de funcția selectată
switch selectedFunction
case 'plus'
result = operand1 + operand2;
case 'minus'
result = operand1 - operand2;
case 'times'
result = operand1 * operand2;
case 'rdivide'
if operand2 ~= 0
result = operand1 / operand2;
else
% Afișează mesaj de eroare pentru împărțirea la zero
uialert(app.UIFigure, 'Eroare: Împărțire la zero!', 'Eroare', 'Icon', 'error');
return;
end
case 'uplus'
result = +operand1;
case 'uminus'
result = -operand1;
case 'ldivide'
result = operand1 \ operand2;
case 'power'
result = power(operand1, operand2);
case 'mtimes'
result = mtimes(operand1, operand2);
otherwise
% Afișează mesaj de eroare pentru funcție necunoscută
uialert(app.UIFigure, 'Eroare: Funcție necunoscută!', 'Eroare', 'Icon', 'error');
return;
end
% Aici creăm o celulă pentru rezultat și un nou rând pentru tabel
newRow = {selectedFunction, result};
% Convertiți rezultatul la un format potrivit pentru adăugare în tabel
newRow{2} = result;
% Verificăm dacă dimensiunile rândurilor din tabel sunt aceleași cu noul rând
if isempty(app.ResultTable.Data) || isequal(size(app.ResultTable.Data{end, :}), size(newRow))
% Adăugăm rândul în tabel
if isempty(app.ResultTable.Data)
% Dacă tabelul este gol, setează direct data
app.ResultTable.Data = newRow;
else
% Dacă tabelul conține deja date, extinde dimensiunea pentru a adăuga un nou rând
app.ResultTable.Data = [app.ResultTable.Data; newRow];
end
end
% Exemplu: Reprezentare grafică a argumentelor și a rezultatului în Axes
cla(app.UIAxes); % Curățăm Axele înainte de fiecare reprezentare
switch argumentType
case 'Scalar'
% Reprezentare cu marcatori pentru scalari
plot(app.UIAxes, [0, 1], [0, operand1], '-o', 'DisplayName', 'Operand1');
hold(app.UIAxes, 'on');
plot(app.UIAxes, [0, 1], [0, operand2], '-s', 'DisplayName', 'Operand2');
plot(app.UIAxes, [0, 1], [0, result], '-d', 'DisplayName', 'Rezultat');
legend(app.UIAxes, 'Location', 'Best');
case 'Vector'
% Reprezentare cu linii pentru vectori
plot(app.UIAxes, operand1, '-o', 'DisplayName', 'Operand1');
hold(app.UIAxes, 'on');
plot(app.UIAxes, operand2, '-s', 'DisplayName', 'Operand2');
plot(app.UIAxes, result, '-d', 'DisplayName', 'Rezultat');
legend(app.UIAxes, 'Location', 'Best');
case 'Matrice'
% Afișează matricea în UIAxes folosind imshow
imagesc(app.UIAxes, result);
colormap(app.UIAxes, 'jet');
colorbar(app.UIAxes);
axis(app.UIAxes, 'image');
end
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure('Visible', 'off');
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = 'MATLAB App';
% Create UIAxes
app.UIAxes = uiaxes(app.UIFigure);
title(app.UIAxes, 'PlotAxes')
xlabel(app.UIAxes, 'X')
ylabel(app.UIAxes, 'Y')
zlabel(app.UIAxes, 'Z')
app.UIAxes.Position = [35 242 300 185];
% Create FunctionListBoxLabel
app.FunctionListBoxLabel = uilabel(app.UIFigure);
app.FunctionListBoxLabel.HorizontalAlignment = 'right';
app.FunctionListBoxLabel.Position = [392 416 90 22];
app.FunctionListBoxLabel.Text = 'FunctionListBox';
% Create FunctionListBox
app.FunctionListBox = uilistbox(app.UIFigure);
app.FunctionListBox.Items = {'plus', 'uplus', 'minus', 'uminus', 'times', 'rdivide', 'ldivide', 'power', 'mtimes'};
app.FunctionListBox.ValueChangedFcn = createCallbackFcn(app, @listBoxValueChanged, true);
app.FunctionListBox.Position = [497 366 100 74];
app.FunctionListBox.Value = 'plus';
% Create ArgumentTypeButtonGroup
app.ArgumentTypeButtonGroup = uibuttongroup(app.UIFigure);
app.ArgumentTypeButtonGroup.SelectionChangedFcn = createCallbackFcn(app, @radioButtonsValueChanged, true);
app.ArgumentTypeButtonGroup.Title = 'ArgumentTypeButtonGroup';
app.ArgumentTypeButtonGroup.Position = [474 226 123 106];
% Create ScalarButton
app.ScalarButton = uiradiobutton(app.ArgumentTypeButtonGroup);
app.ScalarButton.Text = 'Scalar';
app.ScalarButton.Position = [11 60 58 22];
app.ScalarButton.Value = true;
% Create VectorButton
app.VectorButton = uiradiobutton(app.ArgumentTypeButtonGroup);
app.VectorButton.Text = 'Vector';
app.VectorButton.Position = [11 38 65 22];
% Create MatriceButton
app.MatriceButton = uiradiobutton(app.ArgumentTypeButtonGroup);
app.MatriceButton.Text = 'Matrice';
app.MatriceButton.Position = [11 16 65 22];
% Create ResultTable
app.ResultTable = uitable(app.UIFigure);
app.ResultTable.ColumnName = {'Column 1'; 'Column 2'; 'Column 3'; 'Column 4'};
app.ResultTable.RowName = {};
app.ResultTable.Tag = 'ResultTable';
app.ResultTable.Position = [314 21 302 185];
% Create ExecutButton
app.ExecutButton = uibutton(app.UIFigure, 'push');
app.ExecutButton.ButtonPushedFcn = createCallbackFcn(app, @ExecuteButtonPushed, true);
app.ExecutButton.Position = [65 78 100 23];
app.ExecutButton.Text = 'Execută';
% Create Label
app.Label = uilabel(app.UIFigure);
app.Label.HorizontalAlignment = 'right';
app.Label.Position = [25 171 25 22];
app.Label.Text = '';
% Create Operand1EditField
app.Operand1EditField = uieditfield(app.UIFigure, 'text');
app.Operand1EditField.Position = [65 171 100 22];
% Create Label_2
app.Label_2 = uilabel(app.UIFigure);
app.Label_2.HorizontalAlignment = 'right';
app.Label_2.Position = [25 132 25 22];
app.Label_2.Text = '';
% Create Operand2EditField
app.Operand2EditField = uieditfield(app.UIFigure, 'text');
app.Operand2EditField.Position = [65 132 100 22];
% Show the figure after all components are created
app.UIFigure.Visible = 'on';
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = app1
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
Voss
Voss on 29 Jan 2024
Edited: Voss on 30 Jan 2024
"the results of any Array or Matrices operations are not shown into the result table"
Refer to my example GUI code, specifically the part where I convert the result to a character vector for storage in the table:
str = mat2str(val1+val2);

Sign in to comment.

Categories

Find more on Data Type Identification in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!