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:
Question on array maniupulation

Subject: Question on array maniupulation

From: Darin

Date: 30 Sep, 2010 18:34:22

Message: 1 of 4

Hi,

i need a fast way to do something like this

%Initialize
for i = 1:10
z(i) = rand()
end


%Actual part i need help with....
count = 0;
for i = 1:10

if z(i) > 0.5
k(count) = z(i)
end
end

Any ideas? I know i can do something like m = (z > 0.5) but i dont know how to get rid of the zeros fast...

Subject: Question on array maniupulation

From: James Tursa

Date: 30 Sep, 2010 18:45:23

Message: 2 of 4

"Darin " <dmccoy@mail.bradley.edu> wrote in message <i82l7e$ptm$1@fred.mathworks.com>...
> Hi,
>
> i need a fast way to do something like this
>
> %Initialize
> for i = 1:10
> z(i) = rand()
> end

z = rand(1,10);

>
>
> %Actual part i need help with....
> count = 0;
> for i = 1:10
>
> if z(i) > 0.5
> k(count) = z(i)
> end
> end
>
> Any ideas? I know i can do something like m = (z > 0.5) but i dont know how to get rid of the zeros fast...

Your example code doesn't work because count starts at 0, an invalid index. Assuming that what you meant was count starting at 1 and incrementing with every instance of z(i) > 0.5 you could do this using logical indexing:

k = z(z>0.5);

James Tursa

Subject: Question on array maniupulation

From: Matt Fig

Date: 30 Sep, 2010 18:46:21

Message: 3 of 4

Is this what you are trying to do?

% Data
z = rand(1,10)
% Count how many elements are greater than .5
m = sum(z>.5)

Subject: Question on array maniupulation

From: Sean

Date: 30 Sep, 2010 18:48:20

Message: 4 of 4

"Darin " <dmccoy@mail.bradley.edu> wrote in message <i82l7e$ptm$1@fred.mathworks.com>...
> Hi,
>
> i need a fast way to do something like this
>
> %Initialize
> for i = 1:10
> z(i) = rand()
> end
>
>

z = rand(10,1);

> %Actual part i need help with....
> count = 0;
> for i = 1:10
>
> if z(i) > 0.5
> k(count) = z(i)
> end
> end

z(z>0.5) ?
or
sum(z>.5)
Your above code would fail since count will always be zero and you can't reference k(0)

>
> Any ideas? I know i can do something like m = (z > 0.5) but i dont know how to get rid of the zeros fast...

Tags for this Thread

No tags are associated with 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