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:
Intelectual puzzle (eliminte the for loop)

Subject: Intelectual puzzle (eliminte the for loop)

From: Michael

Date: 23 Nov, 2010 16:31:05

Message: 1 of 4

Hello Everyone,

The following code construct matrix of with 3 col and 10 rows. I want to multiple each element by its corresponding row value. I have done this several ways using a nested four loop, and if statment and the code below. So I in a sense have a solution (3 in fact) that work; however, is there a way to make the code more efficent (if I had a very large matrix) and eliminate the for loop?

vertical = (horzcat(linspace(1,10,10)',linspace(11,20,10)',linspace(21,30,10)'));
output = zeros(size(vertical));

for loop1=1:numel(vertical)
   [row col] = ind2sub(size(vertical), loop1);
    output(loop1) = vertical(loop1)*row;
 
end

Subject: Intelectual puzzle (eliminte the for loop)

From: Matt Fig

Date: 23 Nov, 2010 16:43:04

Message: 2 of 4

bsxfun(@times,vertical,(1:size(vertical,1)).')

Subject: Intelectual puzzle (eliminte the for loop)

From: Sean de

Date: 23 Nov, 2010 16:44:04

Message: 3 of 4

"Michael" <michael.lisowski@gentex.com.extrachar> wrote in message <icgq89$h8b$1@fred.mathworks.com>...
> Hello Everyone,
>
> The following code construct matrix of with 3 col and 10 rows. I want to multiple each element by its corresponding row value. I have done this several ways using a nested four loop, and if statment and the code below. So I in a sense have a solution (3 in fact) that work; however, is there a way to make the code more efficent (if I had a very large matrix) and eliminate the for loop?
>
> vertical = (horzcat(linspace(1,10,10)',linspace(11,20,10)',linspace(21,30,10)'));
> output = zeros(size(vertical));
>
> for loop1=1:numel(vertical)
> [row col] = ind2sub(size(vertical), loop1);
> output(loop1) = vertical(loop1)*row;
>
> end

I.e. this?
output = bsxfun(@times,vertical,(1:size(vertical,1)).');


-Sean

Subject: Intelectual puzzle (eliminte the for loop)

From: Michael

Date: 23 Nov, 2010 18:58:03

Message: 4 of 4

Sean
> output = bsxfun(@times,vertical,(1:size(vertical,1)).');
>
Thanks. I did not know the function you used existed. But it is something I will try to remember.

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