MATLAB: Trying to not display the logical array in this code - matlab

This is a function that checks if the array that is inputted is a square matrix. The function is doing what I want, namely checking if the array is square, but it also outputs the logical array that I am using to check if the number of rows equals the number of columns.
function isSquare = checkSquare(x)
[rnum, cnum] = size(x);
isSquare = rnum == cnum;
if isSquare == 1
fprintf('True')
else
fprintf('False')
end
end

I think it's because you're running the function without putting a semicolon at the end.
>> checksquare(zeros(4,4))
True
ans =
logical
1
>>
Instead, try this.
>> checksquare(zeros(4,4));
True>>
It would be nicer for the formatting to print a newline character after True or False. Change fprintf('True') to fprintf('True\n') and fprintf('False') to fprintf('False\n') and you'll get the following result.
>> checksquare(zeros(4,4));
True
>>

Related

How to write a function which compares two vectors to see if they have the exact same values by making use of another function?

function [tf] = findelt1(w,x)
tf=0;
for i=1:length(w)
if any(w(i)==x)
tf=1;
return;
end
end
end
using findelt1 how can I write a function method1(v,w), v and w being two input vectors, which returns true if all values in v and w are the same and returning false otherwise.
Pseudo code:
default output is true
for each element a in v
% use findelt1 that you wrote above
if a is not in w, return false
So far for method1 I have:
function [tf] = method1(v,w)
tf=1;
for i=1:length(v)
for j=1:length(w)
if findelt1(w,j)==1
if v(i)==w(j)
tf=1;
else
tf=0;
end
end
return;
end
end
end
Original Answer:
This will make sure they are the same length and that all elements agree. It also checks that the order is the same. Ex. v=[1 2 3] & w=[3 2 1] will return false
tf = numel(v) == numel(w) && all(v == w);
Updated Answer:
Just use isequal it checks size and contents. #CitizenInsane beat me to it in the comments.
tf = isequal(v,w)

Numeric Data Validation While Loop in Matlab

I have a function usenum
function TF = usenum(x)
TF = false;
if ~isnumeric(x)
h = msgbox('Input is not numeric');
elseif (x <= 0)
h = msgbox('Input must be > 0');
else
TF = true;
end
I am getting user input in the main menu:
answer = inputdlg(prompt,dlg_title,num_lines,def);
The inputdlg has 2 values and can be indexed by {1} and {2}
I want to wait for the user to input a value, the value has to be a number and greater than 0. in the case that he doesn't, I want to output the respective message and make him keep inputting until he gets it right, or close the inputdlg dialog.
I am attempting something like this:
condition = false;
while ~condition
answer = inputdlg(prompt,dlg_title,num_lines,def);
numOfTracks = answer{1};
bpmRange = answer{2};
condition = usenum(numOfTracks);
end
I am trying to say, while condition = false, i.e. while input is not numeric or not greater than 0, keep getting user input. Once the user inputs a valid number the condition is supposed to become true and the while is supposed to terminate. However, the inputdlg keeps opening for input and the only way I can stop it is by closing it (infinite loop). how can I achieve what I want?
Thanks in advance
Your loop appears to be correct. The following testing provides results of your usenum function.
>> usenum('')
ans =
0
>> usenum(-1)
ans =
0
>> usenum(1)
ans =
1
Your usenum function is correct as far as typing is concerned, but I believe your input is always given as a string since you're getting user input from a dialogue. Instead, you should try redefine usenum as follows if you're expecting a string input. The function str2double converts it to a double and if it's text, it will show as NaN. That's what the isnan check is for, to check if it's text.
function TF = usenum(x)
% Default to false
TF = false;
x = str2double(x);
% Check if digits
if isnan( x )
h = msgbox('Input is not numeric');
elseif (x <= 0)
h = msgbox('Input must be > 0');
else
TF = true;
end
This is the result of the new function.
>> usenum('a')
ans =
0
>> usenum('-1')
ans =
0
>> usenum('1')
ans =
1

Matlab: If condition working on empty matrices, not working properly

My variables and their values, in the if condition statement
leftoverROI1s{1}= [11 15];
missinglabelsinimage{1} is an empty matrix.
I want to execute a for loop only if both my conditions in the if statement are true, i.e.:
if ~isempty(leftoverROI1s{1}) && ~isempty(missinglabelsinimage{1})
for % loop for each element in non-empty `missinglabelsinimage` structure array.
% Add a scalar to each element of non-empty `missinglabelsinimage` structure array
...
end % end for loop
end % end if
My program control is going into for loop (which I expect, it shouldn't if there is an empty missinglabelsinimage{1}) and the control is working on missinglabelsinimage{1} (empty matrix), which obviously gives me an error as I am trying to add a scalar to my 'non-empty' missinglabelsinimage{1}.
I am not able to understand the error in my if condition. Any help would be appreciated.
PS: I checked the above variables
~isempty(missinglabelsinimage{1})
ans =
0
~isempty(leftoverROI1s{1})
ans =
1
missinglabelsinimage{1}
ans =
Empty matrix: 1-by-0
I suspect there is a typo somewhere in code that you are not showing. Reducing your example to its most basic form (always a good idea to try to find a bug):
a = [];
b = [1 2 3];
display(~isempty(a))
display(~isempty(b))
if ~isempty(a) && ~isempty(b)
disp('we passed the if')
else
disp('we are in the else')
end
Results in the output
ans =
0
ans =
1
we are in the else
Exactly as you would expect. If you get something different, then the code you are using isn't the code you are showing... is there a similar (mistyped) variable somewhere? Try doing a clear all, then run a minimal example that reproduces your problem.

matlab: converting a vector to a cell array of strings

I'm sure there's a way to do this but I don't know what it is.
Suppose I have a vector
v = [1.02 2.03 3.04];
and I want to convert this to a cell array using a format string for each element:
' %.3f'
(3 spaces before the %.3f)
How can I do this? I tried the following approach, but I get an error:
>> f1 = #(x) sprintf(' %.3f',x);
>> cellfun(f1, num2cell(v))
??? Error using ==> cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
As stated in the error, just provide the parameter of UniformOutput as false
cellfun(f1, num2cell(v), 'UniformOutput', false)
ans =
' 1.020' ' 2.030' ' 3.040'
Here is another solution:
>> v = [1.02 2.03 3.04];
>> strcat({' '}, num2str(v(:),'%.3f'))
ans =
' 1.020'
' 2.030'
' 3.040'
Obviously you can transpose the result if you want a row vector.
You can also use the {} syntax:
cellfun(#(x){f1(x)}, num2cell(v))
Also check out : Applying a function on array that returns outputs with different size in a vectorized manner

Matlab how to ignore the first index=1

The code below gives me error = Subscript indices must either be real positive integers or logicals.Because the first index using FIND function is i=1, the i-1 gives negative value. How to ignore when i==1 without using the LOOP function
fid=fopen('data.txt');
A=textscan(fid,'%f%f%f%f');
fclose(fid);
in = cell2mat(A);
i = find(in(1:end,2)>20 & in(1:end,2) <50);
out=in;
s(i)=sqrt((out(i,3)-out(i-1,3))*(out(i,3)-out(i-1,3))+(out(i,4)-out(i-1,4))*(out(i,4)-out(i-1,4)));
fid = fopen('newData.txt','wt');
format short g;
fprintf(fid,'%g\t%g\t%g\t%g\n',out',s'); %'# Write the data to the file
fclose(fid);
you can try something like this:
i = find(in(1:end,2)>20 & in(1:end,2) <50);
i = i(find( i > 1));
By the way, be careful of using i as a regular variable because you're overriding the default value of:
i = sqrt(-1)