Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
How to code this as vector operation? [cell manipulation]

Subject: How to code this as vector operation? [cell manipulation]

From: Pete sherer

Date: 11 Nov, 2010 22:03:04

Message: 1 of 4

Hi,

Is there anyway I can replace this FOR loop with a vector operation?

x = {'ABC','XX','CCCC','S','ZZ'}';
y = [1 10 3 4 567]';

tmp = cell(5,1);
for ii = 1:5
    tmp(ii) = {[x{ii} num2str(ii)]};
end

tmp =
    'ABC1'
    'XX2'
    'CCCC3'
    'S4'
    'ZZ5'

Thank you very much in advance.
Pete

Subject: How to code this as vector operation? [cell manipulation]

From: Sean

Date: 11 Nov, 2010 22:19:03

Message: 2 of 4

"Pete sherer" <tsh@abg.com> wrote in message <ibhp6o$gme$1@fred.mathworks.com>...
> Hi,
>
> Is there anyway I can replace this FOR loop with a vector operation?
>
> x = {'ABC','XX','CCCC','S','ZZ'}';
> y = [1 10 3 4 567]';
>
> tmp = cell(5,1);
> for ii = 1:5
> tmp(ii) = {[x{ii} num2str(ii)]};
> end
>
> tmp =
> 'ABC1'
> 'XX2'
> 'CCCC3'
> 'S4'
> 'ZZ5'
>
> Thank you very much in advance.
> Pete

Yes it is possible, it may not be faster:
tmp = cellfun(@(x,y){[x num2str(y)]},x,num2cell(y))

Subject: How to code this as vector operation? [cell manipulation]

From: Matt Fig

Date: 11 Nov, 2010 23:10:04

Message: 3 of 4

"Sean " <sean.dewolski@nospamplease.umit.maine.edu> wrote in message
> Yes it is possible, it may not be faster:
> tmp = cellfun(@(x,y){[x num2str(y)]},x,num2cell(y))


This would be faster than cellfun:

tmp2 = arrayfun(@(x,y)sprintf('%s%i',x{:},y),x,y,'Un',0);

However, as Sean points out, this is even faster (on my machine anyway):

tmp3 = cell(length(x),1);
for ii = 1:length(x)
    tmp3{ii} = sprintf('%s%i',x{ii},y(ii));
end

Note that I assume the use for y, even though you do not show it that way in your example.

Subject: How to code this as vector operation? [cell manipulation]

From: Jan Simon

Date: 11 Nov, 2010 23:18:04

Message: 4 of 4

Dear Pete,

Not vectorized, but faster:
  x = {'ABC','XX','CCCC','S','ZZ'}';
  % y = [1 10 3 4 567]'; % Not needed at all?!
  tmp = cell(5,1);
  for ii = 1:5
      tmp{ii} = [x{ii} sprintf('%d', ii)];
  end

Jan

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us