Display strings and variable - cell array

12 次查看(过去 30 天)
I want to disply the output of my variable. so i created the following code.
food= { 'Rice','Quinoa','Tortilla','Lentils','Broccoli' }';
X % X is the output
for n =1:length(X)
disp(food{X(ii)})
end
The code is not working. Any help will be appreciated.

回答(1 个)

ANKUR KUMAR
ANKUR KUMAR 2021-3-15
编辑:ANKUR KUMAR 2021-3-15
Access the contents of cells by indexing with curly braces, {}.
food= { 'Rice','Quinoa','Tortilla','Lentils','Broccoli' }';
for n =1:length(food)
disp(food{n})
end
  5 个评论
ANKUR KUMAR
ANKUR KUMAR 2021-3-15
Please clear all the pre defined variables before running the code.
Index cannot be float. It must be an integer.
Below is the working complete code.
clc
clear
food= { 'Rice','Quinoa','Tortilla','Lentils','Broccoli' }
X=[2,5]
for n =1:length(X)
disp(food{X(n)})
end
Telema Harry
Telema Harry 2021-3-17
Thanks for the feedback. The code did work. However this is not the outcome I wanted.
I wanted to display, values of my X variable. X values are output from my optimization function.
Each index of my X(i) corresponds to same index in the food array.
Displaying only the values of X(i), one will not know the food associated with it. That is why i want to display the string i.e. food. associated with the value of X.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Food Sciences 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by