Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird cell array behavior

Tags:

matlab

I am familiar with python, but this is only my second day using matlab.

I understand that

a = {1 2 3}
fprintf('%i %i %i', a{1:3})

yields

1 2 3

But how come

a = {1 2 3}
fprintf('%i %i %i', a)

gives an error?

I would really like for

fprintf('%i %i %i', {1 2 3}{1:3})

to yield

1 2 3

In other words, if I have a cell array, how do I print each element with fprintf without assigning the cell array to a variable?

Any advice is appreciated.

EDIT: To elaborate: I have a challenge set to receive user input to get the name of an experiment, current date, and end date (of the experiment) and then output all of this information as well as the number of days left until the experiment concludes. I want to do this with only one line of code. My code is as follows.

fprintf(strcat(...
'\nTest: %s',...
'\nCurrent Date: %s',...
'\nEnd Date: %s',...
'\nNumber of days until completion: %i\n'...
),input('\nTest name?\n','s'),...
feval(@(dates){dates{1},dates{2},diff(datenum(dates,'mm-dd-yyyy'))},...
{input('\nCurrent Date? (mm-dd-yyyy)\n','s')...
input('\nEnd Date? (mm-dd-yyyy)\n','s')}));    

When this code is run I receive an error that essentially boils down to the problem described above, but I wanted to stick to basic examples. This should clear up why I don't want to just use a variable defined previously - there is no previously defined variable.

like image 622
vim Avatar asked Jun 30 '26 15:06

vim


1 Answers

A cell array is just another data type, so when you enter

a = {1 2 3}
fprintf('%i %i %i', a)

the fprintf function just sees the single variable 'a' and knows that a cell array is not compatible with fprintf.

When you index into a cell array using curly brackets {}, however, matlab returns a "comma-separated list," which can be input directly into functions as if you were writing out those values manually. So

fprintf('%i %i %i', a{1:3})

is interpreted as

fprintf('%i %i %i', 1, 2, 3)

For your second question, as you've found Matlab generally doesn't allow you to chain indexing operations onto other operations. So I think you do have to assign the cell array to a variable first.

like image 116
Matt Avatar answered Jul 03 '26 09:07

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!