帮助在 Matlab 中使用紧凑数组运算来替换 for 循环

发布于 2024-11-05 08:34:14 字数 709 浏览 0 评论 0原文

我需要模拟森林火灾,为此,我需要一个色彩图。 颜色图有 51 行,如下所示:

前 10 行是从深绿色到黄色的渐变,行的生成方式为:

uint8color = [4 112 31];
for i = -1:8
    cmap = double(uint8(uint8color + i*[30 27 3])) / 255
end;

接下来是一条蓝色线:

cmap(11, :) = [0 0.5 0.9];

其余 40 行从黄色到红色到几乎黑色,完成通过以下内容:

for i=19:-1:-20
    farve = double(uint8(uint8farve + i*[12 12 5])) / 255;
end;

这工作得很好,但是,我想尽可能避免使用循环,并尝试使用 Matlab 能够执行的紧凑数组操作,

尽管如此,我仍然坚持上述内容,没有意识到如何(以及如果)我可以使用紧凑表示法,但手头仍然有索引。

对于前 10 行,类似于:

cmap(1:10, :)

将替换 for 循环,但它需要我以某种方式仍然提取索引并从值中减去 2 (1:10 -> -1:8)

我希望有一个 Matlab某处的大师,谁能指出我正确的方向

提前致谢

I need to simulate a forest fire and for this, I need a colormap.
The colormap has 51 rows, which looks like this:

First 10 is a gradient from dark green to yellow and the rows are generated by:

uint8color = [4 112 31];
for i = -1:8
    cmap = double(uint8(uint8color + i*[30 27 3])) / 255
end;

Next is a single blue line:

cmap(11, :) = [0 0.5 0.9];

And the remaining 40 lines go from yellow over red to almost black, done by the following:

for i=19:-1:-20
    farve = double(uint8(uint8farve + i*[12 12 5])) / 255;
end;

This works fine, however, I would like to avoid using loops wherever possible and try to use the compact array-operations Matlab is capable of

I'm quite stuck with the above though, not realising how (and if) I can use the compact notation, but still have the index at hand.

For the first 10 rows, something like:

cmap(1:10, :)

Would substitute the for-loop, but it would require me to somehow still extract an index and subtract 2 from the value (1:10 -> -1:8)

I hope there's a Matlab guru somewhere, who can point me in the right direction

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦纸 2024-11-12 08:34:14

第一个循环可以重写为:

uint8color = [4 112 31];
i = (-1:8)';
cmap = double(uint8(repmat(uint8color, length(i), 1) + i*[30 27 3])) / 255;

不过,我不太确定您想要通过所有这些强制转换实现什么目标......

The first loop can be rewritten as:

uint8color = [4 112 31];
i = (-1:8)';
cmap = double(uint8(repmat(uint8color, length(i), 1) + i*[30 27 3])) / 255;

I'm not quite sure what you're trying to achieve with all those casts, though...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文