tags:

views:

67

answers:

1
A=rand(10)
B=find(A>98)

How do you have text saying "There were 2 elements found" where the 2 is general i.e. it isn't text, so that if I changed B=find(A>90) it would automatically no longer be 2.

+7  A: 
some_number = 2;
text_to_display = sprintf('There were %d elements found',some_number);
disp(text_to_display);

Also, if you wanted to count the number of elements greater than 98 in A, you should one of the following:

numel(find(A>98));

Or

sum(A>98);

sprintf is a very elegant way to display such data and it's quite easy for a person with a C/C++ background to start using it. If you're not comfortable with the format-specifier syntax (check out the link) then you can use:

text_to_display = ['There were ' num2str(some_number) ' elements found'];

But I would recommend sprintf :)

Jacob
If you don't care about saving a string, you can skip the call to disp, by simply calling `fprintf` (and not saving any output) which will output to the display also. Note that you may wish to add `\n` to ensure a new line appears.
Geoff
@Geoff - `disp` tacks the newline on for you. Also, you can just do `disp(sprintf(...))` or `disp(['There were ' ...]) to avoid the temp variable.
mtrw
@mtrw: disp adds three newlines, and thus wastes valuable screen real estate. Therfore, I'd go with fprintf unless you have to keep the string around.
Jonas
@Jonas - I'd forgotten about that. FWIW, in Octave `disp` uses up just one line.
mtrw