Display strings and variable - cell array

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일

0 개 추천

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

Telema Harry
Telema Harry 2021년 3월 15일
Thank you for your feedback. I have not assigned anything to the cell.
X currently contains the values of my output variable. And each index corresponds to an index in the array food. Assuming X = [1;2;3;4;5]; I want to display the following
Rice = 1;
Quinoa = 2
Tortilla = 3
Lentils = 4
Broccoli = 5;
Assigning variable X to food will probably be the best way to do it. So how can I assign X to food?
It is not necessary to assign X to food.
If you have specific indices in X to choose from food variable, you can use this chunk of code
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월 15일
i am getting error. Don't know why? Please see screenshot.
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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

제품

릴리스

R2021a

질문:

2021년 3월 15일

댓글:

2021년 3월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by