MatLab strcat and fprintf function [duplicate] - matlab

I get the following error message about too many input arguments in my fprintf function. But it seems to me that just the right amount of arguments were passed.
All this is in the context of a guide GUI I made (see picture at the end).
Error while evaluating uicontrol Callback
calibration button hit
20
200
10
10
2520
25197
2520
25197
'C0 2520 25197 10 10'
Error using serial/fprintf (line 115)
Too many input arguments.
Error in UserInterface>StaticCalibrationBtn_Callback (line 202)
fprintf(handles.s, 'C0 %s %s %s %s',StartStepsStr,EndStepsStr,Increment,Wait);
Here is the code
function StaticCalibrationBtn_Callback(hObject, eventdata, handles)
% hObject handle to StaticCalibrationBtn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
disp('calibration button hit');
Start = str2double(get(handles.CalFromUserTxt, 'string')); % Fetches the user inputed start location in mm and converts to double
disp(Start);
End = str2double(get(handles.CalToUserTxt, 'string')); % same for End position
disp(End);
Increment = get(handles.CalUserIncrementTxt, 'string'); % fetches the increment user inputed data as a string
disp(Increment);
Wait = get(handles.CalUserSpeedTxt, 'string'); % fetches the wait inputed data as a string
disp(Wait);
StartSteps = round(Start/0.00793750000); % computes the starting step position,double division
disp(StartSteps);
handles.StartSteps = StartSteps; % creats a place for the start steps inside the handles structure, to be fetched by anythingelsest be saved with guidata(hObject,handles)
EndSteps = round(End/0.00793750000); % computes the end step position
disp(EndSteps);
handles.EndSteps = EndSteps; % stores the end steps to be accessed by anything else must be saved with guidata(hObject,handles)
StartStepsStr = num2str(StartSteps); % converts the StartSteps double into a string so it can be sent over serial as a string
disp(StartStepsStr);
EndStepsStr = num2str(EndSteps); % converts the EndSteps double into a string so it can be sent over serial as a string
disp(EndStepsStr);
OutputString = strcat('C0' , {' '} , StartStepsStr , {' '} , EndStepsStr , {' '} , Increment , {' '} , Wait);
disp(OutputString);
fprintf(handles.s, 'C0 %s %s %s %s',StartStepsStr,EndStepsStr,Increment,Wait);
and where handles.s comes from
function SerialBtn_Callback(hObject, eventdata, handles)
% hObject handle to SerialBtn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA
comPort = get(handles.COMportTxt,'String');
if(~exist('serialFlag','var'))
[handles.s, handles.serialFlag] = setupSerial(comPort);
end
guidata(hObject,handles);
end
And the setupserial funciton
function [ s, flag] = setupSerial(comPort)
%Initialize serial port communication between Arduino and Matlab
%Ensure that the arduino is also communicating with Matlab at this time.
%if setup is complete then the value of setup is returned as 1 else 0.
flag =1;
s = serial(comPort);
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',9600);
set(s,'Parity','none');
fopen(s);
a='b';
while (a~='a')
a=fread(s,1,'uchar');
end
if (a=='a')
disp('serial read');
end
fprintf(s,'%c','a');
mbox = msgbox('Serial Communication setup.'); uiwait(mbox);
fscanf(s,'%u');
end
USING THE FOLLOWING RESOLVED THE ISSUE
OutputString = sprintf('C0 %s %s %s %s',StartStepsStr,EndStepsStr,Increment,Wait);
fprintf(handles.s,'%s', OutputString);

There are multiple functions called fprintf, one for files, one for serial objects and some others. You are using functionally which you know from the fprintf for files, but you are using it with a serial object. Check the right documentation which can be accessed via doc serial/fprintf

Related

writing elements in matlab listbox

I am trying to write a list in a listbox.
code:
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
error = getappdata(0, 'error_norm');
rows = size(error,1);
for i = 1:rows
set(handles.listbox1,'string',strcat('filt_',num2str(i)));
for j = 1:length(error)
set(handles.listbox1,'string',strcat('sig_',num2str(i),'_',num2str(j)));
for k = 1:length(error{j}.main)
set(handles.listbox1,'string',strcat('seg_',num2str(i),'_',num2str(j),'_',num2str(k)));
end
end
end
Where error is a array of structure, this array contains filters, singals in these filters, segments of these signals. based on the number of all these components, i want to write the list. I want to write something like this in the listbox:
filt_1
sig_1_1
seg_1_1_1
seg_1_1_2
sig_1_2
seg_1_2_1
seg_1_2_2
But apparently, 'set' function overwrites the elements, so all i am getting is 1 element and the last element.
Any suggestion to how to overcome this problem will be appreciated.
Yes, since set always overwrites the string, it is better to firstl build the string and then pass it to set.
Example
% Sample data
rows=4;
error=cell(1,5);
for i=1:length(error)
error{i}.main=rand(1,4);
end
% Build string
str={};
for i=1:rows
str{end+1}=sprintf('filt_%i',i);
for j=1:length(error)
str{end+1}=sprintf('sig_%i_%i',i,j);
for k=1:length(error{j}.main)
str{end+1}=sprintf('seg_%i_%i_%i',i,j,k);
end
end
end
% Set data
set(handle.listbox1,'String', str);
Depending on the size of the final string it might be a good idea to preallocate str for performance.

Writing Data to Text file for every five Minute Matlab

Suppose vec_A, vec_B, vec_c are some matrices with random data. I want to write data to text file for every 5 min, My code as follows:
function samplegui_OpeningFcn(hObject, ~, handles, varargin)
handles.timer = timer(...
'ExecutionMode', 'fixedRate', ... % Run timer repeatedly
'Period', 300, ... % Initial period.
'TimerFcn', {#open,hObject}); % Specify callback
handles.output = hObject;
handles.vec_A=[];
handles.vec_B=[];
handles.vec_C=[];
guidata(hObject, handles);
function open_Callback(hObject, eventdata, handles) % push button to receive serial data.
cnt=0;
while 1
% Getting data from Serial Port
get_lines=fgets(handles.se) % getting data from serial port
if~isempty(get_lines)
cnt=cnt+1;
if strfind(get_lines,'T') %Parsing data
handles.vec_A=[handles.vec_A;[timet newword]];
plot(handles.vec_A(:,1),handles.vec_A(:,2:end),'r'); % plotting
% Same follows for parsing and plot vec_B and Vec_C
drawnow(); % to update the Plots
end
end
Pause(.05);
start(handles.timer); % saving the data
dlmwrite('My_sample1.txt',handles.vec_A);
dlmwrite('My_sample2.txt',handles.vec_B);
dlmwrite('My_sample3.txt',handles.vec_C);
stop(handles.timer);
end
guidata(hObject, handles);
While running my code, following error occurs:
Error while evaluating TimerFcn for timer 'timer-6'
Too many input arguments.
How to execute timer in this case to write data successfully for every five minutes or suggest any other way to do it.
You have defined your TimerFcn to be {#open, hObject} but you don't have a function named open. Instead, it is trying to call the built-in open with three input arguments (the timer object, an event object, and hObject) and this is producing the error because open only accepts one input argument.
That being said, it's not clear at all how the code that you have provided will accomplish anything close to what you want. Something like this may work better.
function samplegui_OpeningFcn(hObject, ~, handles, varargin)
handles.timer = timer(...
'ExecutionMode', 'fixedRate', ... % Run timer repeatedly
'Period', 300, ... % Initial period.
'TimerFcn', #(s,e)write_data()); % Specify callback
handles.output = hObject;
handles.vec_A=[];
handles.vec_B=[];
handles.vec_C=[];
guidata(hObject, handles);
start(handles.timer);
%// Now update your data in a loop
cnt = 0;
while true
%// Getting data from Serial Port
get_lines = fgets(handles.se)
if ~isempty(LINES)
cnt = cnt + 1;
if strfind(LINES, 'T')
handles.vec_A = [handles.vec_A; [timet newword]];
plot(handles.vec_A(:,1), handles.vec_A(:,2:end),'r');
drawnow
end
end
end
function write_data()
%// Write it to file
dlmwrite('My_sample1.txt',handles.vec_A);
dlmwrite('My_sample2.txt',handles.vec_B);
dlmwrite('My_sample3.txt',handles.vec_C);
end
end

Creating tic/toc vector in MATLAB GUI

I built a GUI using the GUIDE feature in Matlab. I have many push buttons. I start by clicking one push button to start tic. Then when I click any of the other push buttons, I want to build a vector of toc time stamps. How do I do this?
The most robust solution is to store and manipulate the vector in the GUI's handles structure. First, in your "create function", initialize the start and stop vectors:
function yourGui_CreateFcn ( hObject , eventdata , handles )
% Initialize the start and stop vectors.
handles.timeStart = [];
handles.timeStop = [];
% Update the GUI handles structure.
guidata ( hObject , handles );
end
Then, in your first button, start the timer and store it to your handles vector.
function button1_Callback ( hObject , eventdata , handles )
% Start the timer, updating the value in the handles structure.
handles.timeStart = tic;
% Update the GUI data so that timer is available to other functions.
guidata ( hObject , handles );
end
Next, in each of your other button callbacks, retrieve the starting time from the handles structure and determine the elapsed time:
function button2_Callback ( hObject , eventdata , handles )
% Retrieve the start time.
timeStart = handles.timeStart;
% Determine the elapsed time.
timeElapsed = toc ( timeStart );
% Store the new value in the handles structure.
handles.timeStop(end+1,1) = timeElapsed;
% Update the guidata.
guidata ( hObject , handles );
end
Finally, you can output the values from the GUI using the "output function".
function yourGui_OutputFcn ( hObject , eventdata , handles )
% Specify the output variables.
varargout { 1 } = handles . timeStart;
varargout { 2 } = handles . timeStop;
end
You would then execute your gui using the following statement in the command line:
>> [timeStart,timeStop] = yourGui ( );

Matlab - How to interdict to leave an edit text if there are errors?

I am trying to make a GUI in wich you have to complete many edit text items, and in each edit text's callback I have to check if the value/values introduced is/are good. If a value is not correct, an Error Message will inform the user about what is wrong. Also, if the value in an edit text is not good, the user shouldn't be able to move to another edit text. I tried many solutions, but none did exactly what I want. In the next code the problem is that the user is allowed to go to another uicontrol and if i don't introduce any value, it doesn't cosider the string to be null. Please help if you can. Tnx
function edit_keyboard_Callback(hObject, eventdata, handles)
% hObject handle to edit_keyboard (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_keyboard as text
% str2double(get(hObject,'String')) returns contents of edit_keyboard as a double
global matrix
global input_method
if input_method == 1
matrixString = get(hObject,'String');
[lines colums] = size(matrixString);
k=1;
if isempty(get(hObject,'String'))
msg = msgbox(['Complete A'],'Empty !','warn')
return;
else
for i=1:lines
temp = explodeString(matrixString(i,:),' ')
cl = length(temp)
for j=1:cl
[num flag] = str2num(char(temp(j)));
if flag~=1
msg = msgbox(['Error in line ' num2str(j) ', colum ' num2str(i) ' , input a number! '],'Not a number!','warn')
return;
else
matrix(i,j) = num;
end
end
end
end
end

How to read multiple lines by individual in an edit text with a value of Max=5 in Matlab?

I have in my gui an edit text field that accepts multiple lines with a Max value of 5, and i can't find a way to display a matrix with the input values...something like this:
m=[m(1) m(2) m(3) m(4) m(5)];
set(handles.show,'string',m)
how can i store the values in the calculate callback..every time i run this, it brings me an error..
function masa_Callback(hObject, eventdata, handles)
% hObject handle to masa (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%h_edit is the handle to the edit box
m=str2double(get(hObject,'String'));
function calculate_Callback(hObject, eventdata, handles)
% hObject handle to agregarm (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
f = str2double(get(h_fuerza,'string')); %h_edit is the handle to the edit box
m = str2double(get(h_masa,'string')); %h_edit is the handle to the edit box
[row, column] = size(m);
for i = 1:row
eval(m{i,:}) %evaluate each line as in MATLAB command prompt
end
I have the masa_callback,rigidez_callback and fuerza_callback i try to read the user input in the edit text box...so i want to pass those values to the calculate_callback as an array to perform certain operations according to the value of n...the error that i am getting is that when for example n=2, i add two values in the masa_callback column and fuerza_callback and 3 values in the rigidez_callback, those values are passed to the case n==2, and when my program tries to display for example the matrix m, it displays all the values i enter together in the spaces of m(1) and m(2)...i want to put only each separated value, not joined together!...How can i fix this,, i believe that is whith an array and a loop but i dont know how, and how to pass the array values to the equation to perform operations(as numbers) and display it as string
To fix the problem with the input (assuming you have your data in some cell array, and that handles.show refers to a text box), use strvcat:
someCellArray = {'a','b'};
m = strvcat(someCellArray{:});
set(handles.show,'string',m)
Your problem stems from the line
m = str2double(get(h_masa,'string'));
You do not want to convert the string to double.
Since the String property actually returns a multiline string, you have to modify your code like this:
m = get(h_masa,'String');
nRows = size(m,1);
for iRow = 1:nRows
eval(m(i,:));
end