MATLAB: Generalizing an IF and FPRINTF expression

fprintfifMATLAB

Hello,
I got a part of code looking like this:
A = ... % can be a scalar or a vector
B = ... % can be a scalar or a vector if A is scalar
if any(B-A) <= 0 && length(B-A) == length(B)
fprintf('B > %g or A < %g',A,B(1,find(B-A<=0,1)))
return
elseif any(B-A) <= 0 && length(B-A) == length(A)
fprintf('B > %g or A < %g',A(1,find(B-A<=0,1)),B)
return
end
A and B can't both be vectors at the same time. They can both be scalars at the same time
Is there a way to have only one FPRINTF ?
It would need the code not to acces out of (1,1) for the scalar variable.
It's to have less lines in the final code. I would use it elsewhere too. It may be a bit perfectionism but would be usefull.
Thank you in advance for answering.
EDIT: actually the question is "How to return 1 if the index exceeds matrix dimensions" ?

Best Answer

Since your actual question is much easier to understand, I'll try to answer that one. Below you will find two strategies that ensure you will either get a specific index, or index 1. I removed some of the logic you had, and I also edited the find in the second strategy.
I would also urge you to have a look at the doc for any, as any(B-A) <= 0 is equivalent to ~any(B-A)
%example A and B
A=4;
B=[5 2 1 9];
ind_A=find(B-A<=0,1);
ind_B=find(B-A<=0,1);
if ind_A>size(A,2),ind_A=1;end
if ind_B>size(B,2),ind_B=1;end
fprintf('B > %g or A < %g\n',A(1,ind_A),B(1,ind_B))
%or:
ind=find(B<=A,1);%ind=find(B-A<=0,1);
fprintf('B > %g or A < %g\n',...
A(1,min(ind,end)),B(1,min(ind,end)))
The trick in the second one is that within an indexing context, the end keyword will also work in another function call.