help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Please, help me vectorize this code


From: michele
Subject: Re: Please, help me vectorize this code
Date: Sun, 17 Sep 2017 16:08:16 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.3.0

On 09/17/2017 01:15 PM, Pablo Fernández Bustamante wrote:
Hi,

I want the elements of a matrix M_ to be equal to those of an original matrix M but only if they satisfy a certain condition, otherwise write a zero.

The following lines of code work as expected but I want to avoid the
loop if it is possible.

>> M = floor(rand(5, 4)*10);
>> [r, c] = find(M > 4);
>> M_ = zeros(5, 4);
>> for n = 1:length(r)
M_(r(n), c(n)) = M(r(n), c(n));
endfor

I have tried

M_ = M(find(M>4));

but that returns a column vector of the elements which satisfy the condition.

Thanks in advance,

Pablo




_______________________________________________
Help-octave mailing list
address@hidden
https://lists.gnu.org/mailman/listinfo/help-octave


You can do like this:

M = floor(rand(5,4)*10);
M1 = zeros(5,4);
M1(M>4) = M(M>4);

Bests,

--
Michele Ginesi




reply via email to

[Prev in Thread] Current Thread [Next in Thread]