Matlab特定向量构建及无循环累加求和技术咨询
Hey there! Let's work through your two MATLAB vector tasks step by step—no fancy tricks required, just straightforward, easy-to-follow code that plays to MATLAB's strengths with vectorized operations.
1. Creating the sine vector
x_j = sin(π(j-1)/10) for j=1,...,21 MATLAB excels at handling entire arrays at once, so we can skip writing loops entirely here. Here's how to do it:
- First, generate the sequence of
jvalues from 1 to 21:j = 1:21; - Then calculate the sine values for each element in one go. Notice that
(j-1)shifts our starting point to 0 (when j=1) up to 20 (when j=21), which is exactly what we need for the argument of the sine function:x = sin(pi*(j-1)/10); - If you want to write it in a single line (even cleaner!), you can directly use the shifted sequence
0:20instead of definingjfirst:
This gives you a 21-element vector where each entry matches the formula you provided.x = sin(pi*(0:20)/10);
2. Creating the linear vector
x_j = 2 - j for j=0,...,20 + loop-free summation Again, vectorized operations make this super simple:
- First, generate the
jvalues from 0 to 20:j = 0:20; - Compute the vector
xby subtracting each element ofjfrom 2—MATLAB automatically applies this operation to every element in the array:x = 2 - j; - For the summation, forget about writing a
forloop! MATLAB has a built-insum()function that handles this in one line:
This function will add up all elements oftotal_sum = sum(x);xefficiently, no loops needed.
A quick tip: Vectorized operations like these aren't just shorter to write—they're also way faster than loops in MATLAB, especially for larger arrays. Once you get the hang of them, they'll save you tons of time!
内容的提问来源于stack exchange,提问作者Ryan Porter
相关产品推荐
相关产品推荐

