I'm trying to use a while loop to delete the final row in an array every time it loops, however, it's not working
Show older comments
Basically, using the file TensileData.xlsx that I have attached to the question, I have to use a loop, work backwards through the entire data set reducing the number of points to find the equation of the elastic region. This can be done by calculating the r^2 value until the r^2 value is larger than 0.9997. However, when I try to create write the code for this I am unable to do it. I'm not completely sure where to begin, however, I have made a start. When I run the code I receive the error: Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in lab8t5 (line 26)
strain(numRows_strain, :) = [];

The code that my question relates to is part b onwards, however, I have put all the code here in case it is helpful.
clear all; close all; clc
% Part a.
data = importdata('TensileData.xlsx');
strain = data.data(:, 1);
stress = data.data(:, 2);
figure(1)
plot(strain, stress, 'r*')
% Part b.
numRows_strain = length(strain);
numRows_stress = size(stress, 1);
[a0, a1, r2] = linreg(strain, stress);
slope = a1;
constant = a0;
error = r2;
while error <= 0.9997
[a0, a1, r2] = linreg(strain, stress);
numRows_strain = numRows_strain - 1;
numRows_stress = numRows_stress - 1;
strain(numRows_strain, :) = [];
stress(numRows_stress, :) = [];
end
Accepted Answer
More Answers (1)
Richard Burnside
on 14 Sep 2023
Edited: Richard Burnside
on 14 Sep 2023
0 votes
I think you could just do something vectorized like this:
idx = find(r2>0.9997);
stress(idx) = [];
strain(idx) = [];
Also I think "error" is a Matlab function so you should avoid using it as a variable.
Categories
Find more on Function Creation 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!