Write a program that generates a vector with 30 random integers between –20 and 20 and then finds the sum of all the elements that are divisible by 3.use matlab
时间: 2024-03-18 10:38:46 浏览: 80
产生30个介于0至50之间的不同的随机数(VB)
4星 · 用户满意度95%
Here's the MATLAB code to generate a vector of 30 random integers between -20 and 20, and then find the sum of all the elements that are divisible by 3:
```
% Generate a vector of 30 random integers between -20 and 20
vec = randi([-20, 20], [1, 30]);
% Find the sum of all the elements that are divisible by 3
divisible_by_3 = mod(vec, 3) == 0;
sum_divisible_by_3 = sum(vec(divisible_by_3));
```
In the first line, we use the `randi` function to generate a row vector of 30 random integers between -20 and 20. In the second line, we create a logical vector `divisible_by_3` that is true for any element of `vec` that is divisible by 3 (i.e., the remainder after division by 3 is 0). Finally, we use the `sum` function to sum up only the elements of `vec` that are divisible by 3. The result is stored in the variable `sum_divisible_by_3`.
阅读全文