How to loop through each row of a column, then loop through the remaining columns?

8 ビュー (過去 30 日間)
L 2022 年 5 月 24 日
編集済み: Matt J 2022 年 5 月 24 日
Hi all, I am very new to coding and MATLAB, so please bear with me here:
I have a large spreadsheet of data that I have divided into separate groups (i.e., group 1 = data(:, 1:3), group 2 = data(:, 4:5), and so forth. Each data point is a textual response (e.g., "apple"), which I want to convert to a corresponding numeric response (e.g., "0" for "apple").
I have created a function for the text to number conversion, which I would like to iterate through each row of a column, then repeat for a certain number of columns (i.e., for group 1, I would repeat this procedure from column 1 to column 3).
My current code achieves this for column 1, but repeats the column 1 output in column 2 and 3 (instead of converting the ACTUAL text responses in column 2 and 3).
How can I fix this so that the code properly converts each column? Thank you so much in advance.
group1_responses = data(:,1:3);
[rows, cols] = size(group1_responses);
group1_values = zeros(rows, cols);
for i = 1:cols
for j = 1:rows
response = group1_responses{j};
group1_values(j, i) = group1_text_to_val(response);
function [val] = group1_text_to_val(text)
if text == "apple"
val = 0;
elseif text == "banana"
val = 1;
elseif text == "orange"
val = 2;
elseif text == "grape"
val = 3;
elseif text == "pear"
val = 4;
val = NaN;


Voss 2022 年 5 月 24 日
response = group1_responses{j};
response = group1_responses{j,i};

その他の回答 (2 件)

Matt J
Matt J 2022 年 5 月 24 日
編集済み: Matt J 2022 年 5 月 24 日
If your group1_responses is a cell or string array, there is no need to distinguish between rows and columns at all. Just do,
group1_responses={'apple', 'banana';'orange','grape';'pear','pineapple'}
group1_responses = 3×2 cell array
{'apple' } {'banana' } {'orange'} {'grape' } {'pear' } {'pineapple'}
for k = 1:numel(group1_values)
group1_values(k) = group1_text_to_val(group1_responses{k});
group1_values = 3×2
0 1 2 3 4 NaN

Jon 2022 年 5 月 24 日
It's a little hard to tell without having the values for your matrix data to try this with, but it looks like you should modify your assignment of response to
response = group1_responses(i,j);


Community Treasure Hunt

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

Start Hunting!

Translated by