sully_r
sully_r

Reputation: 131

Using num2str with matrices in Octave

Having issue with the num2str function in Octave.

My code:

>> alpha = zeros(1,length(alpha));
>> legendInfo = zeros(1,length(alpha));
>> legendInfo(1) = num2str(alpha(1));

Error Message:

error: A(I) = X: X must have the same size as I

I've been trying to follow this link to no avail: Link

Update:

Based on suggestion, I have implemented the following code and have received the following error message:

>> labelInfo = cell(1,numel(alpha))
>> labelInfo{1} = num2str(alpha{1});

error: matrix cannot be indexed with {

error: evaluating argument list element number 1

ANSWER

The answer provided was accurate with one tweak:

Parantheses rather than curly braces.

Thanks!

Upvotes: 0

Views: 470

Answers (1)

Suever
Suever

Reputation: 65430

You have initialized legendInfo to be a numeric array the same size as alpha. When you convert alpha(1) to a string, it is possibly more than 1 character long (i.e. alpha(1) > 9) which is obviously not going to fit into a single element in an array.

length(num2str(10))
%   2

length(legendInfo(1))
%   1

Also, even if num2str(alpha(1)) yields a string that has a length of 1, it will implicitly convert it to a number (it's ASCII representation) which is likely not what you want.

legendInfo = zeros(1, numel(alpha));
legendInfo(1) = num2str(1);
%  49    0    0

Rather than a numeric array, you likely want a cell array to hold the legend info since you will have strings of varying lengths.

legendInfo = cell(1, numel(alpha));
legendInfo{1} = num2str(alpha{1});

If you look closely at the post you have linked, you'll see that they use the curly brackets {} to perform assignment rather than parentheses () indicating that they are creating a cell array.

Upvotes: 4

Related Questions