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.

1 Answer 1

7
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 :)

Sign up to request clarification or add additional context in comments.

4 Comments

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 - disp tacks the newline on for you. Also, you can just do disp(sprintf(...)) or `disp(['There were ' ...]) to avoid the temp variable.
@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 - I'd forgotten about that. FWIW, in Octave disp uses up just one line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.