How to loop through each row of a column, then loop through the remaining columns?
72 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Voss
on 24 May 2022
Replace:
response = group1_responses{j};
with:
response = group1_responses{j,i};
0 Comments
More Answers (2)
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_values=zeros(size(group1_responses));
for k = 1:numel(group1_values)
group1_values(k) = group1_text_to_val(group1_responses{k});
end
group1_values
0 Comments
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);
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!