用Matlab中的字符串foreach循环 [英] foreach loop with strings in Matlab

查看:2973
本文介绍了用Matlab中的字符串foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有效的是:

  for i = 1:3 
if(i == 1)
b ='cow';
elseif(i == 2)
b ='dog';
else
b ='cat';
end

disp(b);
end

结果是:

  cow 
dog
cat

但我想要的是更优雅的东西,看起来像:

  for i = ['cow','dog ','cat'] 
disp(i);
end

并给出相同的结果



有没有在Matlab的选项做到这一点?



附加:

我需要以后的字符串作为字符串,而不仅仅是显示( disp 仅仅是一个例子)。我已经尝试在我的真实程序中使用单元格数组:

  clear all; 
关闭所有;
clc;

全球fp_a
全球TEST_TYPE
全球SHADE_METHODE

为fp_a = 11:24
为shade = {'full','fast '}
SHADE_METHODE =阴影(1);
for test = {'bunny','city'}
TEST_MODE = test(1);
fprintf('fp_a:%d | test:%s | shade:%s',fp_a,TEST_TYPE,SHADE_METHODE);
ray_tracing;
end
end
end

值保持单元格而不是字符串我得到错误消息:


???错误使用==> fprintf函数没有为'cell'输入定义。

* - 我并不需要 fprintf 我只是用它来检查值是否正确。
$ b

** - ray_tracing 是我使用字符串值的代码

  for i = {'cow','dog','cat'} 
disp(i {1})
结尾

结果:

  cow 
dog
cat


I want to create a loop that will iterate over several strings, but unable to do so in Matlab.

What works is:

for i=1:3
  if (i==1)
    b='cow';
  elseif (i==2)
    b='dog';
  else
    b='cat';
  end

  disp(b);
end

and the result is:

cow
dog
cat

But what I want is something more elegant that will look like:

for i=['cow','dog','cat']
  disp (i);
end

and give the same result.

Is there an option in Matlab to do this?

ADDITION:

I need the words as strings later on to use and not just to display (the disp was just as an example). I've tried to use cell arrays in my real program:

clear all;
close all;
clc;

global fp_a
global TEST_TYPE
global SHADE_METHODE

for fp_a=11:24
for shade={'full','fast'}
    SHADE_METHODE=shade(1);
    for test={'bunny','city'}
        TEST_MODE=test(1);
        fprintf ('fp_a:%d | test: %s | shade: %s',fp_a,TEST_TYPE,SHADE_METHODE);
        ray_tracing;
    end
end
end

It doesn't work as the values stay as cells and not strings I get the error message:

??? Error using ==> fprintf Function is not defined for 'cell' inputs.

*-I don't really need the fprintf I just use it to check that the values are correct.

**-ray_tracing is my code that uses the values of the strings

解决方案

Or you can do:

for i={'cow','dog','cat'}
   disp(i{1})
end

Result:

cow
dog
cat

这篇关于用Matlab中的字符串foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆