Why am I getting this error when selecting files with uigetfile? - matlab

I used uigetfile to select multiple images. When I select the images and push the open button or press the enter key everything is okay. But when I instead select the images and double click on the selected images, I get this error:
Cell contents reference from a non-cell array object.
Error in Picketfence>insertpb_Callback (line 141)
file = fullfile(PathName,FileNames{i});
Here's my code:
c={'*.*', 'All Files(*.*)';'*.jpeg','figure (*.jpg)';'*.tif',...
'figure (*.tif)'};
[FileNames,PathName] = uigetfile(c, 'Select Images','MultiSelect','on');
if char(FileNames)
nfiles = length(FileNames);
handles.profile = zeros(1024,1024);
for i = 1:nfiles
file = fullfile(PathName,FileNames{i});
handles.profile = handles.profile+im2double(imread(file));
end
end
Why am I getting this error and how can I fix it?

The problem is that you can't select multiple files by double-click. When you select your files, then double-click on one of them, what's actually happening is that you are selecting only the one you double-clicked on. In other words, the first click of the double-click selects just that one, clearing the others.
When the GUI closes and returns to your code, you only have a single file selected, so FileNames isn't a cell array, just a character string. This is why the cell content indexing with {} fails.
A few more points about your code...
Your conditional check if char(FileNames) is wrong. The char function doesn't return logical (i.e. boolean) values. It converts things to character arrays. As per the documentation for uigetfile, the outputs will be zero when the selection is cancelled or the GUI closed, so the appropriate check in your case would be:
if ~isequal(FileNames, 0)
% Do your processing here...
else
% Nothing was selected; take some other action
end
You may want to account for the possibility of only 1 file being selected, thus having FileNames be a character array. The simplest way to do this is to first check if FileNames is a character array using ischar, and if so encapsulate it in a 1 element cell array (since your code expects cell arrays):
if ischar(FileNames)
FileNames = {FileNames};
end
Then you can do all your processing as you have it written above.

Related

Find an unsuppressed line in a large script

I am running a script which is fairly large. In the output screen I get ans = 10.
The problem is that the code is very large and I cannot pin point where this output is coming from.
Are there any tips to find the origin of this output within the MATLAB environment since I prefer not to have a random output on the screen?
In the case of a single script file, you can programmatically invoke mlint to return all warnings in the form of a struct:
L = mlint('my_filename'); % No need for .m at the end
Inspecting the structure you could see the following:
This structure has a field named 'message' which contains various issues, among which is what we're after - 'Terminate statement with semicolon to suppress output (in functions).'. At this stage you can run
find( strcmp({L.message},... % output is not suppressed on purpose
'Terminate statement with semicolon to suppress output (in functions).') )
Then inspect the line numbers that get printed.
Alternatively, if you want to skip the variable editor, or want to inspect a whole folder of .m files, you can run mlintrpt (in the case of a folder) or mlintrpt('plotWithoutOutliers') (in the case of a single file) and get a report in the following form:
As Luis said: look for the mlint error. In code this is shown as an orange shaded = and orange wiggle beneath it; on the scroll bar on the right it shows an orange line which you can hover over to see what the warning is and click on to go to the warning.
Additionally I included the red errors for completion. These will cause your code to be unable to run. Same here, red wiggle + red line on the right.
Last, the square on the top right, by the arrow, will either be green (no problems), orange (warnings, but the code will be able to run usually) or red (code won't be able to run).
Used Dev-iL's answer to create a simple function that will tell you the lines of code that are not suppressed. This way you don't need to inspect the returned lines in the structure L. Example: lines = UnsuppressedLines('isEven.m')
function [lines] = UnsuppressedLines( matlabScript)
l = mlint(matlabScript);
unsuppressedInstances = find( strcmp({l.message},'Terminate statement with semicolon to suppress output (in functions).') )
if isempty(unsuppressedInstances)
fprintf('No unsuppressed lines in script')
lines = [];
else
lines = {l.line};
lines = lines(unsuppressedInstances);
end
end

Using matlab GUIDE to produce a modal dialog that records user inputs?

I am new to using the matlab GUIDE. I know there are some predefined dialog boxes such as inputdlg and msgbox and warndlg and so on and so forth that can easily be implemented into the command line without having to play around with too many things.
However, I was wondering whether it was possible to modify inputdlg in matlab guide? I am just trying to produce a simple dialog box that reads the user input and when the user clicks ok, it closes and records the inputs somewhere. Using inputdlg it is very easy to do so:
uiwait(msgbox(sprintf('Please enter your new references for each electrode.')));
prompt = {'Fp1','Fp1','F7','T3','T5'};
dlg_title = 'Input references';
num_lines = 1;
answer = inputdlg(prompt,dlg_title,num_lines );
The user enters a string for each option 'Fp1', 'F7' and so on and all these answers are recorded in "answer".
Now I have 2 problems:
I have 16 such inputs and if I put them all inside the same "prompt" then the dialog box runs off the screen - so I use prompt, prompt2 and prompt3 to split them up and record the answers. It works fine, but it would be better if I could arrange the input boxes side by side as you can edit/drag inside the matlab guide.
I want my dialog box to look as it does in this picture with the minus sign between the 2 cells where the user will enter something into both boxes. The first box in each line is actually equivalent to the prompt that I have specified above, but in this case the user will enter the string into the first cell rather than being prompted for it.
But I can't seem to figure out how to do this either using inputdlg itself and altering its properties or using guide to create a custom inputdlg.
Does anybody have any advice?
Update
I have added some lines of code in the correct places and I am able to now store the user input to a variable. However, I have around 32 edit boxes and my current method means I will have 32 different inputs... I do not want this, I want them all to be recorded inside the same array.
The code I added was in the edit box callback function:
input = get(hObject, 'String')
display(input)
assignin('base','input',input);
% Save the value
handles.trial = input
guidata(hObject,handles)
This is from editbox1 and I have tried to proceed as
input = get(hObject, 'String')
A(1,:) = input
assignin('base','A',A(1,:));
but in this case it returns A as a cell which has the value entered in the last edit box.
Can anyone help?
First you should make matlab wait for the user to respond. Locate the OpeningFcn of you GUI. The last line should look like that
% uiwait(handles.figure1);
You should uncommon the line. Next, you have to resume the UI when the user clicks OK. This is done by inserting the line
uiresume(handles.figure1);
in the OK button callback. When the users clicks OK, the OutputFcn will be called. There you can return the values you need via varargout cell array. Finally, in the last line of OutputFcn, you should close your GUI using
close(hObject)
All the names I used are the matlab's defaults. If you changed any of them, modify the code accordingly.

Libreoffice/Openoffice Calc - append string to cells

I need to add .jpg at the end of all he cells in one or more columns
9788895249971 into > 9788895249971.jpg
9788867230129 into > 9788867230129.jpg
9788867230273 into > 9788867230273.jpg
9788867230280 into > 9788867230280.jpg
Detailed step-by-step instructions are much appreciated since I am very new to Calc.
Thanks
Do you need to do this once or is this going to be a repeated task every week/month?
If it is something you need to do just once, here is what you can do:
Next (right) to the column where your numbers are open (insert) a new column.
Assuming the following: Numbers are in column A, New column is column B.
In this new column B in the top cell (B1) write:
=A1&".jpg"
Now copy B1 all the way down to the end. In B1 type [Ctrl]+c then Hold [Shift] and hit [PgDn] until the end then press [Ctrl]+v.
Highlight Column B, [Ctrl]+c, then [Edit] [Paste Special] values only (No formula's) this freezes the calculated data.
This is just another option,
just click the function wizard and select concatenate, in that enter which column you want to enter as text1 as and second column in text2. Then when you click OK you will get an concatenated column like below image
so in the C column you will get as a1.jpg.
For those who continue to find this question (as I did):
This can be quickly done using regular expression option of find and replace. (I don't know what version of Calc introduced regex searches, but 6.2.4 has it.)
If you only want to update some non-blank cells on the sheet, select them.
Choose Find and Replace.
On the dialog, fill in the following:
Enter $ for the Find value. ($ means end of line in regex, or in this context end of cell value.)
Enter the desired suffix (.jpg in the question) for the Replace value.
Check Regular Expressions under Other Options
Check Current Selection Only under Other Options if you want to limit to the cells selected in step 1.
Uncheck All Sheets unless that is what you want.
Choose Replace All
This will update the values in-place and does not require any additional columns or formulas.
There's a much more elegant way to do this that doesn't require sacrificing cells just to hold data types, and can be scaled to work with one cell or a large chart range.
Add both pieces of data into the =CONCAT() function
Make sure to use CONCAT instead of CONCATENATE, as `CONCAT accepts cell ranges and is more dynamic.
Open the Function Wizard on the cell in question, and build the following function:
=CONCAT(<your_data>," <suffix>",...)
# Make sure to add a space before the suffix so it appears in the cell.
# You can use this with as many input variables as required letting
# you add as many strings, formulas, or numbers together.
The result should be something like this. In my example, the cell in question is the final value of Ethereum on a balance sheet:
The above example was an easy one, since it was being used as a test, all my summed values were ints, if I had floating point numbers, they would run away to max decimal places (not very pretty).
The function will drag out and expand intelligently to other cells like any other formula.
Adjusting accuracy of floating point values inside a CONCAT function
Sometimes, adding a cell results in a rounding problem, or an extreme amount of decimal places. You can further nest your function using ROUND(<your_data>,<decimal_places>)
Your function would look like this:
=CONCAT(ROUND(<cell_range>, ".jpg")
In your specific case, you don't need a space in the second argument as you want to append .jpg directly to the end of the string.
`
Using Macros to automate the entire process
This is extremely repeatable, and using the Macros feature, you can automate these to make much more simplified functions that allow you to enter just the variables you need, while the macro does the work in the background.
Based on Emmanuel Angelo R.’s answer, I would advice learning to differentiate between fixed cell references and dynamic ones. The following applies:
Cell A1 contains the suffix you would like to add, e.g. ‘.jpg’
Row 2 contains headings, e.g. B2 = ‘Old Filename’ and ‘New Filename’
Cells A3:A¹ contain your filenames
Cells B3:B contain you concatenation formula
In cell B3, type =concatenate(A3;$a$1).² If your locale requires comma as separator, replace my semicolons with commas. Copy cell B3 by selecting it and pressing Ctrl + C. Move the cursor to cell A3, press Ctrl + ↓ (down arror on your cursor keys); this will move you to the bottom of the list of file names. Move your cursor right, then press Ctrl + Shift + ↑; this will select all cells up to the last cell with contents (the one you just wrote your formula in). Press Ctrl + V to paste your contents.
Adding dollar signs in front of your row/column coordinates, will lock that coordinate when pasted. Say you had a list of file types in cells b1–z1 (e.g. jpg, jpeg, tga, bmp, png et c.). An easy way to create the formula would then be by first typing it in cell B3 as =concatenate(A3;B$1), then paste it to every cell till the end of your file names list (cell z3); these cells would then read …A3;b$1, …A3;C$1 et c. When copying it for all the rows below
You could select the entire range of cells with formulas in row 3 and run a search and replace, replacing all instances of ‘A3;’ by ‘A3;$’, effectively inserting a dollar in front of all the cell references, allowing you to, should the need arise, copy it horizontally as well as vertically (the latter being covered by the $ in front of 1).
¹ This means cells from A3 and however far down your sheet goes
² Strictly speaking, it is only necessary to type it as a$1.

result of a callback function in matlab gui

I have created a GUI in matlab with few buttons. Each button when clicked performs a certain function. Now I want to display the calculations being performed in the function to be displayed in a static textbox in the GUI. Is that possible? I am able to display it in the command window by removing the semicolon (;) at the end of the statement but I want it to be displayed in the GUI like a log.
Now when I click the "match" button the following function is called and I want to display whether it matches or not in the GUI in a textbox. Is that possible?
function matchin
[image1, pathname]= uigetfile('*.bmp','Open An image');
Directory = fullfile ('F:','matlab','bin');
D = dir(fullfile(Directory,'*.bmp'));
%imcell = {D.name}';
for i = 1:numel(D)
if strcmp(image1,D(i).name)
disp('matched');
else
disp('not matched');
end
end;
I replaced the code with the one specified in the answer. Without using the text box the output in the matlab command window when I select the second file is
not matched
matched
not matched
not matched
not matched
But if I use a static textbox only the last line is being displayed. How can I display all the 5 lines totally?
Yes, you can do that.
A good practice would be to save a structure with all the handles of your GUI elements by using the function guidata. For more information on this see this link.
Then in your callback you can retrieve this structure, for instance by:
handles = guidata(gcbo);
Then you can set the value of the textbox you want by replacing
if strcmp(image1,D(i).name)
disp('matched');
else
disp('not matched');
end
with:
if strcmp(image1,D(i).name)
set(handles.handle_of_textbox,'String','matched');
else
set(handles.handle_of_textbox,'String','not matched');
end

Handling carriage return/line feed in MATLAB GUI user controls

I have a MATLAB program I am developing in order to do some image processing stuff and need to use a user control into a MATLAB GUI user interface I created ad-hoc.
This user control is a List Box and there I would like to insert some text. Well the problem is not that I cannot put text there, I can do that using this call:
set(handles.mylistbox, 'String', 'MyStringToPrint');
Well the problem is that this call does not let me insert many lines in my list box but just overwrite the previous one.
I wish to find a way to let my code insert the new text in a new line. This should not be so difficult to do and it is also a simple pattern:
texttoprint = 'My text to add'
oldtext = get(handles.MyListBox, 'String') %Holding the previous text here
set(handles.MyListBox, 'String', [oldtext '\n' texttoprint]) %Setting (no line feed printed)
set(handles.MyListBox, 'String', [oldtext char(10) texttoprint]) %Setting (this fails too)
Well it is ok and it does not raise any error BUT, \n DOES NOT WORK.
I do not have any new line... BUT NEED TO!!!!
How should I solve this?
The problem is that I need to print text in this user control, not on the MATLAB commandline (that is very simple just by doing sprintf()).
What to do? Thank you
For a listbox, set the string property to a cell
set(myListboxHandle,'String',{'myFirstLine';'mySecondLine'})
If you want to add another line, call
contents = get(myListboxHandle,'String');
set(myListboxHandle,[contents;{'another line'}])
For multiline text in GUIs otherwise, use char(10) instead of \n, i.e.
set(someUiControlHandle,'String',sprintf('my first line%smy second line',char(10)))
When working with list boxes it's usually easier to deal with the options as a cell array of strings. So, you would initialize your list box as follows:
set(handles.MyListBox,'String',{'Option 1'});
And then you can add options to your list box like so:
newOption = 'Option 2';
oldOptions = get(handles.MyListBox,'String');
set(handles.MyListBox,'String',[oldOptions; {newOption}]);