ruby2
ruby2

Reputation: 11

How to convert a numeric variable to a string in MATLAB

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.

Upvotes: 1

Views: 415

Answers (1)

Jacob
Jacob

Reputation: 34601

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

Upvotes: 7

Related Questions