shawpnik
shawpnik

Reputation: 111

How to write a string in replace of a number in MATLAB?

I am trying to categorise the years based on some conditions. If any year has rainfall less than a specific number it will indicate as a dry year. I have tried the following, but it gives me error "In an assignment A(I) = B, the number of elements in B and I must be the same."

The code is

Year_Category = zeros(ny,1);
for i = 1:ny;
    if (xy(i)< Lower_Limit)
        Year_Category(i) = 'Dry';
    elseif (xy(i)> Upper_Limit)
        Year_Category(i) = 'Wet';
    else
        Year_Category(i) = 'Average';
    end
end

Any help would be appreciated.

Best regards

Upvotes: 0

Views: 23

Answers (1)

rayryeng
rayryeng

Reputation: 104503

You are trying to assign characters to a numeric array. That's why you're getting a dimension mismatch. Each character is a single slot and you can't do that in this case. Use cell arrays instead:

Year_Category = cell(ny,1); %// Change
for i = 1:ny;
    if (xy(i)< Lower_Limit)
        Year_Category{i} = 'Dry'; %// Change
    elseif (xy(i)> Upper_Limit)
        Year_Category{i} = 'Wet'; %// Change
    else
        Year_Category{i} = 'Average'; %// Change
    end
end

Upvotes: 2

Related Questions