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

7 views (last 30 days)
L on 24 May 2022
Edited: Matt J on 24 May 2022
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);
end
end
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;
else
val = NaN;
end
end

Voss on 24 May 2022
Replace:
response = group1_responses{j};
with:
response = group1_responses{j,i};

Matt J on 24 May 2022
Edited: Matt J on 24 May 2022
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'}
group1_values=zeros(size(group1_responses));
for k = 1:numel(group1_values)
group1_values(k) = group1_text_to_val(group1_responses{k});
end
group1_values
group1_values = 3×2
0 1 2 3 4 NaN

Jon on 24 May 2022
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);