sample cell array: A = {[1 2 3], true, \'hi there\', 42, false, \'abc\'} Write a
ID: 3844849 • Letter: S
Question
sample cell array: A = {[1 2 3], true, 'hi there', 42, false, 'abc'}
Write a function, using matlab, named cellParse that has one parameter, a cell array. Each element of the cell array is either a string, a vector of numbers, or a boolean value. The function will return 6 values as follows:
nStr: the number of strings in the cell array
nVec: the number of vectors
nBool: the number of Boolean values
cString: a cell array of all the strings in alphabetic order
vecLength: the average length of all the vectors
allTrue: true if all the Boolean values are true, false otherwise
Suggested approach — do incremental development.
Step 1: set up the function so that it loops over the cell array and returns one value, nStr
Step 2: add to your loop and your output argument so that the function also returns nVec
Step 3: add to your loop and your output argument so that the function also returns nBool
Step 4: You are already counting the number of numeric vectors. Add code that computes the sum of the lengths of all the numeric vectors, and code to compute the average length.
Step 5: You are already counting the number of Boolean elements. Add code that will determine whether all values are true or not.
Step 6: You are already counting the character strings. Add code that will put each character string into a cell array.
Step 7: Add code to sort the cell array of strings
Explanation / Answer
copyable code:
function [nStr nVec nBool cString vecLength allTrue] = cellParse(A)
nStr = 0;
nVec = 0;
nBool = 0;
cString = {};
vecLength = 0;
myval = 0;
allTrue = true;
for index = 1:length(A)
choice= A{index};
switch class(choice)
case 'char'
nStr = nStr + 1;
cString = [cString A(index)];
case 'double'
nVec = nVec + 1;
myval = myval + length(choice);
case 'logical'
nBool = nBool + 1;
allTrue = allTrue & choice;
end
end
if nVec > 0, vecLength = myval ./ nVec;end
cString = sort(cString);
end
output:
>> A = {[1 2 3], true, 'hi there', 42, false, 'abc'};
>> [nStr nVec nBool cString vecLength allTrue] = cellParse(A)
nStr =
2
nVec =
2
nBool =
2
cString =
'abc' 'hi there'
vecLength =
2
allTrue =
0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.