开发者

Dividing selected elements of array on Matlab

开发者 https://www.devze.com 2023-04-09 19:18 出处:网络
I have the following array a = [ 1 10 3 4 68 2 34 8 10 ] And I need to divide each number (/2) if this number is higher than 9.

I have the following array

a = [ 1 10 3 4 68 2 34 8 10 ]

And I need to divide each number (/2) if this number is higher than 9. This means that 1 has not to be divided, and 10 has to be divided (/2)

The resulting array should be:

a = [ 1 5 3 4 34 2 17 8 5 ]

I have to do it without using a FOR function. So I tried with this:

a = a./2;

This divides every number of the array, and I as told you before开发者_如何学运维, I want to divide only the ones higher than 9.

Can anyone tell me how can I do it? Add a 'if whatever>5' in that statement or something?

Thanks in advance


Use logical indexing for both dividing only the numbers that meets your criterion and for assigning the result to those specific indices.

a = [ 1 10 3 4 68 2 34 8 10 ];
a(a>9) = a(a>9) ./ 2
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号