You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在MATLAB的for循环中实现i=i*2的条件(附C循环参考)

Implementing i = i*2 Logic in MATLAB For Loops

Hey there! Let's walk through how to handle this, since MATLAB's loop structure works a bit differently from what you might use in C.

1. Writing i = i*2 in a MATLAB For Loop

MATLAB's for loop doesn’t use the init/condition/update syntax you see in C. Instead, it iterates over a predefined set of values. To get that "double i each time" behavior, you’ve got two solid options:

Option 1: Precompute your sequence of i values

If you know the upper limit for i, generate all the values first and loop through them. For example, starting at 1 and doubling until we hit 100:

% Generates [1, 2, 4, 8, 16, 32, 64]
i_values = 2.^(0:floor(log2(100))); 

for i = i_values
    disp(i); % Swap this out with your actual code
end

This is efficient because MATLAB excels at vector operations, and you avoid modifying the loop variable inside the loop (which is generally not recommended in MATLAB).

Option 2: Use a while loop (C-style feel)

If you want direct control over updating i each iteration, a while loop is your best bet—it mirrors the C structure almost exactly:

i = 1;
while i <= 100
    disp(i); % Your code here
    i = i * 2; % The double step
end

This lets you check the condition, run your code, then update i—just like you would in C.

2. Converting a C For Loop with i = i*2 to MATLAB

Let’s use a real C loop example to make this concrete. Suppose your C code looks like this:

for (int i = 1; i <= 50; i *= 2) {
    printf("Current value of i: %d\n", i);
}

Here’s how to translate this to MATLAB in two ways:

Approach 1: For loop with precomputed sequence

First, build the sequence of i values, then loop through them:

max_limit = 50;
% Calculate how many times we can double 1 before exceeding 50
num_steps = floor(log2(max_limit));
i_values = 2.^(0:num_steps);

for i = i_values
    fprintf("Current value of i: %d\n", i);
end

Approach 2: While loop (direct translation)

This is the most straightforward if you want to keep the same flow as the C loop:

i = 1;
while i <= 50
    fprintf("Current value of i: %d\n", i);
    i = i * 2; % Double i after each iteration
end

This works exactly like the C version—starts at 1, checks if i is ≤50, runs the print statement, then doubles i for the next iteration.

Content of the question originates from Stack Exchange, asked by Eric Garcia

火山引擎 最新活动