MatLab: Error handling of integer input - matlab

How do I in MatLab catch the error that occours when the user enters letters and other things that aren't numbers in the input:
width = input('Enter a width: ');
I have played around for a while with the try/catch command:
width = 0;
message = '';
% Prompting.
while strcmp(message,'Invalid.') || width < 1 || width ~= int32(width)
try
disp(message)
width = input('Frame width: ');
catch error
message = 'Invalid.';
end
end
But with no luck (the above doesn't work). As shown I would like a simple message like "Frame width: " for the user the first time he has to enter his choice. But if an error is caught I want the message for him to be "Invalid. Try again: " fx everytime an error occours.
I have also tried the error() but I don't know how to place that correctly. Since the error() doesn't take the input command, where the error happends, as an argument, it must detect it in another way, which I can't figure.
Any help would be appreciated.

width = input('Frame width: ');
while(~isInt(width))
width = input('Invalid. Try again: ');
end
and you'll have to have the following function somewhere (or another implementation of it)
function retval = isInt(val)
retval = isscalar(val) && isnumeric(val) && isreal(val) && isfinite(val) && (val == fix(val));
end

answer = input('Frame width: ', 's');
[width, status] = str2num(answer);
while ~status || ~isscalar(width) || width ~= floor(width)
answer = input('Invalid. Try again: ', 's');
[width, status] = str2num(answer);
end
disp(width);
(status is 0 if the conversion failed. Without the isscalar test, an input like [1 2; 3 4] would also be accepted. The last test ensures that width must be an integer.)

Related

Excel Range object throws error 0x800A03EC because of a string longer than 255 characters

Using an ActiveX server from MATLAB, I am trying to highlight many cells in an Excel sheet at once. These are not in specific columns or rows so I use Range('A1,B2,...') to access them. However the string accepted by the Range object has to be less than 255 characters or an error:
Error: Object returned error code: 0x800A03EC
is thrown. The following code reproduces this error with an empty Excel file.
hActX = actxserver('Excel.Application');
hWB = hActX.Workbooks.Open('C:\Book1.xlsx');
hSheet = hWB.Worksheets.Item('Sheet1');
col = repmat('A', 100, 1);
row = num2str((1:100)'); %'
cellInd = strcat(col, strtrim(cellstr(row)));
str1 = strjoin(cellInd(1:66), ','); %// 254 characters
str2 = strjoin(cellInd(1:67), ','); %// 258 characters
hSheet.Range(str1).Interior.Color = 255; %// Works
hSheet.Range(str2).Interior.Color = 255; %// Error 0x800A03EC
hWB.Save;
hWB.Close(false);
hActX.Quit;
How can I get around this? I found no other relevant method of calling Range, or of otherwise getting the cells I want to modify.
If you start with a String, you can test its length to determine if Range() can handle it. Here is an example of building a diagonal range:
Sub DiagonalRange()
Dim BigString As String, BigRange As Range
Dim i As Long, HowMany As Long, Ln As String
HowMany = 100
For i = 1 To HowMany
BigString = BigString & "," & Cells(i, i).Address(0, 0)
Next i
BigString = Mid(BigString, 2)
Ln = Len(BigString)
MsgBox Ln
If Ln < 250 Then
Set BigRange = Range(BigString)
Else
Set BigRange = Nothing
arr = Split(BigString, ",")
For Each a In arr
If BigRange Is Nothing Then
Set BigRange = Range(a)
Else
Set BigRange = Union(BigRange, Range(a))
End If
Next a
End If
BigRange.Select
End Sub
For i = 10, the code will the the direct method, but if the code were i=100, the array method would be used.
The solution, as Rory pointed out, is to use the Union method. To minimize the number of calls from MATLAB to the ActiveX server, this is what I did:
str = strjoin(cellInd, ',');
isep = find(str == ',');
isplit = diff(mod(isep, 250)) < 0;
isplit = [isep(isplit) (length(str) + 1)];
hRange = hSheet.Range(str(1:(isplit(1) - 1)));
for ii = 2:numel(isplit)
hRange = hActX.Union(hRange, ...
hSheet.Range(str((isplit(ii-1) + 1):(isplit(ii) - 1))));
end
I used 250 in the mod to account for the cell names being up to 6 characters long, which is sufficient for me.

Why isnt this matlab code working?

I'm trying to write a script to remove comment lines from another script file. Here's what I tried:
fid = fopen('correct_answer.m');
aline = {};
counter = 1;
while ~feof(fid)
aline{counter} = fgetl(fid);
if aline{counter}(1) == '%'
aline{counter} = '';
end
counter = counter + 1;
end
This is the error I get:
Attempted to access aline.%cell(1); index out of bounds because numel(aline.%cell)=0.
Error in hw2 (line 8)
if aline{counter}(1) == '%'
If I run it without the while loop it works fine. What's up with this??
Also if you just happen to know a more simple/efficient approach to removing comment lines that would work too ;)
The problem is that you sometimes read empty lines, and you cannot access the first element of empty lines. Additionally you may have comments at the end of a valid line of code, this code should do the trick
fid = fopen('correct_answer.m');
aline = {};
counter = 1;
while ~feof(fid)
aline{counter} = fgetl(fid);
if ~isempty(aline{counter})
k = strfind(aline{counter}, '%');
aline{counter}(k:end) = '';
end
counter = counter + 1;
end

Extraction of data from DWT subband

I am attempting to extract data from a DWT subband. I am able to embed data correctly (I have followed it in the debugger),cal PSNR etc. PSNR rate seem very high 76.2?? however,I am having lot of trouble extracting data back!It is sometimes extracting the number 128?? Can anyone help or have any idea why this is? I would be very thankful.I have been working on this all day & having no luck!I am very curious to know??
Data Embedding:
coverImage = imread('lena.bmp');
message = importdata('minutiaTest.txt');
%message = 'Bifurcations:';
[LL,LH,HL,HH] = dwt2(coverImage,'haar');
if size(message) > size(coverImage,1) * size(coverImage,2)
error ('message too big to embed');
end
bit_count = 0;
steg_coeffs = [4, 4.75, 5.5, 6.25, 7];
for jj=1:size(message,2)+1
if jj > size(message,2)
charbits = [0,0,0,0,0,0,0,0];
else
charbits = dec2bin(message(jj),8)';
charbits = charbits(:)'-'0';
end
for ii=1:8
bit_count = bit_count + 1;
if charbits(ii) == 1
if HH(bit_count) <= 0
HH(bit_count) = steg_coeffs(randi(numel(steg_coeffs)));
end
else
if HH(bit_count) >= 0
HH(bit_count) = -1 * steg_coeffs(randi(numel(steg_coeffs)));
end
end
end
end
stego_image = idwt2(LL,LH,HL,HH,'haar');
imwrite(uint8(stego_image),'newStego.bmp');
Data Extraction:
new_Stego = imread('newStego.bmp');
[LL,LH,HL,HH] = dwt2(new_Stego,'haar');
message = '';
msgbits = '';
for ii = 1:size(HH,1)*size(HH,2)
if HH(ii) > 0
msgbits = strcat (msgbits, '1');
elseif HH(ii) < 0
msgbits = strcat (msgbits, '0');
else
return;
end
if mod(ii,8) == 0
msgChar = bin2dec(msgbits);
if msgChar == 0
break;
end
msgChar = char (msgChar);
message = [message msgChar];
msgbits = '';
end
end
The problem arises from reading your data with importdata.
This command will load the data to an array. Since you have 39 lines and 2 columns (skipping any empty lines), its size will be 39 2. However, the program assumes that your message will be a string. For example, 'i am a string' has a size 1 13. This expectation of the program compared to the data you actually give it creates all sorts of problems.
What you want is to read your data as a single string, where the number 230 is not one element, but 3 individual characters. Tabs and newlines will also be read in as well.
To read your file:
message = fileread('minutiaTest.txt');
After you extract your message, to save it to a file:
fid = fopen('myFilename.txt','w');
fprintf(fid,message);
fclose(fid);

I got error message about simulink "Output argument is not assigned on some execution paths"

In simulink, I made some model using "MATLAB function"block
but I met error message here.
here is code and error message.
function [VTAS,postVTAS]=fcn(mode,initialVTAS,a,t,preVTAS)
if mode == 1
VTAS = initialVTAS + (a * t) ;
postVTAS = VTAS;
elseif mode == 2
datasize = length(preVTAS);
lastvalue = preVTAS(datasize);
VTAS = lastvalue + 0;
postVTAS = VTAS;
end
end
Output argument 'VTAS' is not assigned on some execution paths.
Function 'MATLAB Function' (#36.25.28), line 1, column 26:
"fcn"
Launch diagnostic report.
I think there is no problem about output "VTAS"
please teach me what is a problems.
As the compiler tells you, under some circumstances there is no output value assigned to VTAS. The reason is that you only assign values to that output if mode is 1 or 2. The compiler doesn't know what values are feasible for mode. To remedy this, you need to make sure that VTAS is assigned under any and all circumstances.
This could be accomplished by, e.g. adding an else construct, like so:
function [VTAS,postVTAS]=fcn(mode,initialVTAS,a,t,preVTAS)
if mode == 1
VTAS = initialVTAS + (a * t) ;
postVTAS = VTAS;
elseif mode == 2
datasize = length(preVTAS);
lastvalue = preVTAS(datasize);
VTAS = lastvalue + 0;
postVTAS = VTAS;
else
VTAS = NaN;
postVTAS = NaN;
end
end
Edit:
Additionally, it would be good practice for the else case to throw an error. This would be helpful for debugging.
As a minor note, for every case, postVTAS is equal to VTAS, so essentially it is superfluous to return both from the function.

Error handling with inputdlg

Below is an input dialog box I'm using in a program. Does anyone know
how to "nicely" handle the case when the user input is not a number?
Also, if the number is outside the range minlev - maxlev then the
error dialog pops up, but you cannot press the OK button because the
input dialog pops up in front of it. Does anyone know how to fix
this?
RVP= 1;
while ( RVP )
prompt = {'Enter the corridor width (1050-1400mm) :'};
dlg_title = 'Input';
num_lines=1;
answer = inputdlg(prompt,dlg_title,num_lines);
if(str2num(answer{1})<1050 || (str2num(answer{1})>1400))
errordlg('Number is out of range');
else
w1 = (2*answer{1}-1050-1400)/(1400-1050)
end
end
Use isnumeric. Then you can re-call the inputdlg after the error dialog.
To keep the errordlg box from being covered up, use uiwait.
while ( RVP )
prompt = {'Enter the corridor width (1050-1400mm) :'};
dlg_title = 'Input';
num_lines=1;
answer = inputdlg(prompt,dlg_title,num_lines);
if ~isnumeric(answer) || (str2num(answer{1})<1050 || (str2num(answer{1})>1400))
uiwait(errordlg('Number is out of range'));
answer = inputdlg({'Please enter a valid input (1050-1400mm) :'},...
dlg_title,num_lines);
end
w1 = (2*answer{1}-1050-1400)/(1400-1050)
end