First cell in a string array is empty, how do I replace this?
Show older comments
Hello everyone,
The code below shows a while loop. I am assigning a Pass or Fail string based on a certain condition. The code works fine but the string array is 1x12 instead of being 1x11. The first cell of this array is also empty and the second cell till the 12th contains the fail or pass string. How can I make sure that the first cell is not empty and has the fail or pass string?
Thank you.
n = 1;
sigma_f = [118.01 97.84 84.51 67.98 58.13 50.29 45.08 41.36 38.58 36.42 34.70];
m_sigma_yf = 280;
s_factor = 5;
mode1_status = strings(size(11));
while n < 12
if sigma_f(n) < m_sigma_yf/s_factor
mode1_status(end+1) = 'Pass';
else
mode1_status(end+1) = 'Fail';
end
n = n+1;
end
2 Comments
Umar
on 10 Jul 2024
Edited: Walter Roberson
on 28 Apr 2025
Hi Dwayn,
Based on the code you provided, it seems like the issue with the first cell being empty in your string array `mode1_status` is due to the initialization of the array with `strings(size(11))`. This creates an array of empty strings with a size of 11, which results in the first cell being empty when you append values to it within the while loop.
To ensure that the first cell is not empty and contains the fail or pass string, you can modify the initialization of `mode1_status` to include an initial value. You can set the first cell of the array to either 'Pass' or 'Fail' before entering the while loop. Here's an updated version of your code:
n = 1;
sigma_f = [118.01 97.84 84.51 67.98 58.13 50.29 45.08 41.36 38.58 36.42 34.70];
m_sigma_yf = 280;
s_factor = 5;
% Initialize as a 1x12 string array
mode1_status = strings(1, 12);
% Set initial value for the first cell
if sigma_f(1) < m_sigma_yf/s_factor
mode1_status(1) = 'Pass';
else
mode1_status(1) = 'Fail';
end
while n < 12
if sigma_f(n) < m_sigma_yf/s_factor
% Adjust index to avoid overwriting initial value
mode1_status(n+1) = 'Pass';
else
% Adjust index to avoid overwriting initial value
mode1_status(n+1) = 'Fail';
end
n = n + 1;
end
By setting an initial value for the first cell of `mode1_status` before entering the while loop and adjusting the index inside the loop, you can ensure that the first cell is not empty and contains the fail or pass string based on your condition.
Feel free to test this updated code and let me know if you encounter any further issues or require additional assistance.
Walter Roberson
on 28 Apr 2025
mode1_status = strings(size(11));
That code does not request a string array of size 11. Instead, it takes the size() of the scalar value 11 (which is 1 x 1) and uses that size as the size of the string array.
Accepted Answer
More Answers (0)
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!